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?
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)
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))
map function in python can be used. It takes two arguments. First argument is the function which has to be used for each element of the list. Second argument is the iterable.
a = [1, 2, 3] map(str, a) ['1', '2', '3']
After converting the list into string you can use simple join function to combine list into a single string
a = map(str, a) ''.join(a) '123'
a=[1,2,3] b=[str(x) for x in a] print b
above method is the easiest and most general way to convert list into string. another short method is-
a=[1,2,3] b=map(str,a) print b
Your problem is rather clear. Perhaps you’re looking for extend, to add all elements of another list to an existing list:
>>> x = [1,2] >>> x.extend([3,4,5]) >>> x [1, 2, 3, 4, 5]
If you want to convert integers to strings, use str() or string interpolation, possibly combined with a list comprehension, i.e.
>>> x = ['1', '2'] >>> x.extend([str(i) for i in range(3, 6)]) >>> x ['1', '2', '3', '4', '5']
All of this is considered pythonic (ok, a generator expression is even more pythonic but let’s stay simple and on topic)
Maybe you do not need numbers as strings, just do:
functaulu = [munfunc(arg) for arg in range(loppu)]
Later if you need it as string you can do it with string or with format string:
print "Vastaus5 = %s" % functaulu