Fix Python – How can I convert each item in the list to string, for the purpose of joining them? [duplicate]

Question

Asked By – AKM

I need to join a list of items. Many of the items in the list are integer values returned from a function; i.e.,

myList.append(munfunc()) 

How should I convert the returned result to a string in order to join it with the list?

Do I need to do the following for every integer value:

myList.append(str(myfunc()))

Is there a more Pythonic way to solve casting problems?

Now we will see solution for issue: How can I convert each item in the list to string, for the purpose of joining them? [duplicate]


Answer

Calling str(...) is the Pythonic way to convert something to a string.

You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with ,:

print(','.join(str(x) for x in list_of_ints))

This question is answered By – Mark Byers

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0