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))
Answer from Mark Byers on Stack OverflowCalling 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))
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))
Python join String with int list - Stack Overflow
How do I use the .join function on integers?
Allow list of integers in `str.join` - Ideas - Discussions on Python.org
Easiest way to join list of ints in Python? - Stack Overflow
You should use much simpler approach:
>>> ''.join(reversed('1 2 3 4'))
'4 3 2 1'
n = 4
arr = map(int, "1 3 4 2".split())
ar = list(arr)
b=ar.reverse()
string =' '
string=string.join(str(ar))
print(string)
There are some mistakes in your code when you use map with int as a parameter the string is splitted to integers and the join function expects strings
One more thing the string.join function does not change the value of the string it just computes the value. If you want your strings value to be changed you should assign explicitly as in the code I have provided
I have a function that can add commas between lists and print them out as strings
def commaCode(listValue):
listValue.insert(-1, 'and')
NewlistValue = ', '.join(listValue)
print(NewlistValue)Here's the output:
cat, bat, and, sat
But I need this to work for integers as well. (and combinations of strings and integers).
How do I use the .join function on integers?
In the past ''.join(list) has worked fine, but I guess now that the things in the list aren't all the same it doesn't. Is there any way to fix this? I was thinking converting all the integers to strings but that didn't work, it still spits out a list