If I have a list of strings, it's easy to output them using .join(). For example:

mylist=['hi', 'there', 'girls']

What I want to know is if there is a builtin python method that acts like join, except it automatically converts ints and floats to strings without giving a Type Error. For example, it would not error with this:

mylist=['hi', 'there', 'girls', 5000]
TypeError: sequence item 1: expected string, int found

I understand that I can simply fix mylist in one line with:

my_newlist=[str(entry) for entry in mylist]

However, this is such a common operation that I thought I'd ask around if there's a way to get .join() or a related module to work this way automatically.

Recommended Answers

All 6 Replies

You mean like this?:

>>> l
['hi', 'there', 600]
>>> newstring=''
>>> for i in l:

>>> newstring


'\t'.join(str(x) for x in mylist)

Hmm, that's essentially what I mean, except using the .join() method to handle the "str(i)" part. The snippet of your code:

for i in l:

Can effectively be replaced by one line using join():


However, unlike in your code, the join() method won't automatically convert the str without some sort of middle step. This is perhaps not a problem, but I just feel like there should be a method to do this, or even like a **kwarg.

''.join(str(i)for i in l)

more convenient, and for newstring=''.join(mylist) it will crah if there are ints in the list, so: ''.join([str(i) for i in l]) suits better.

As this is not performance critical code, this kind of place is one of those that I sometimes like to use the functional map invocation of function to all items:

>>> ''.join(str(i)for i in range(10))
>>> ''.join(map(str, range(10)))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.