+3 votes
in Programming Languages by (11k 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

+1 vote
by (11k points)

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 (15.1k 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 ','

Related questions

...