3

What is the most convenient way to join a list of ints to form a str without spaces?
For example [1, 2, 3] will turn '1,2,3'. (without spaces).

I know that ','.join([1, 2, 3]) would raise a TypeError.

3 Answers 3

6
print ','.join(map(str,[1, 2, 3])) #Prints: 1,2,3

Mapping str prevents the TypeError

Sign up to request clarification or add additional context in comments.

Comments

6
','.join(str(x) for x in ints)

should be the most Pythonic way.

Comments

3

I like ','.join(str(i) for i in lst), but it's really not much different than map

4 Comments

Actually str.join will be faster with a list than with a genexp ;-)
@thefourtheye -- yes, I know. That's well documented for CPython. But in python3.x, the map becomes an iterable (non-list) anyway. Very rarely does that effect the total runtime of your program in any appreciable way though. You'd need to demonstrate that it's a bottleneck before I'd change the code I think.
You don't have to change it, but since lists will be faster, List comprehension is an option.
Yeah, it is ... But I don't like the look of the extra brackets :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.