Join a list of items with different types as string in Python


I need to join a list of items. Many of the items in the list are integer values returned from a function. ie:


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:


Is there a more Pythonic way to solve casting problems?

7/27/2018 5:22:52 PM

Accepted 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 do this:

print ', '.join(str(x) for x in list_of_ints)
8/28/2010 9:09:59 AM

I'm not really sure what you mean by "join", because the grammar you use in your question is pretty bad, but if I understand your question correctly, there's nothing wrong with passing integers to str. One reason you might not do this is that myList is really supposed to be a list of integers e.g. it would be reasonable to sum the values in the list. In that case, do not pass your ints to str before appending them to myList. If you end up not converting to strings before appending, you can construct one big string by doing something like

', '.join(map(str, myList))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow