Hi,

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

mylist=['hi', 'there', 'girls']
myout='\t'.join(mylist)

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]
myout='\t'.join(mylist)
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.

You mean like this?:

>>> l
['hi', 'there', 600]
>>> newstring=''
>>> for i in l:
    newstring+=str(i)


>>> newstring
'hithere600'
>>> 

Edited 4 Years Ago by Lucaci Andrew

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

newstring=''
for i in l:
newstring+=str(i)

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

newstring=''.join(mylist)

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))
'0123456789'
>>> ''.join(map(str, range(10)))
'0123456789'
>>> 
This question has already been answered. Start a new discussion instead.