+3 votes
in Programming Languages by (71.8k points)
I want to convert list items to string to write them to file. Suppose a=[1,2,3,4], I want to write 'a' to file as string '1,2,3,4'. How can I do it?

1 Answer

+3 votes
by (71.8k points)
selected by
 
Best answer

You need to use join function to achieve this. Here is an example to help you out.

>>> a = [1,2,3,4,5,6]
>>> s = ''.join(str(e) for e in a)
>>> s
'123456'
>>> 

Now to put comma between the characters, do the followings.

>>> a = [1,2,3,4,5,6]
>>> s = ''.join(str(e)+"," for e in a)
>>> s.strip(',')
'1,2,3,4,5,6'
>>> 

 

 

by (348k points)
You don't have to use strip is you do the following:

s = ','.join(str(e) for e in a)

Instead of joining with '', join with ','

...