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

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(',')



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