tags:

views:

77

answers:

4

I need to join a list of items many of the items I add to the list is a integer returend value from function i.e

myList.append(munfunc())

how should i convert the returned result to string in order to join it with the list.

did i need to do the following for every integer value : myList.append (str(myfunc()) or this is not the pythonic way to solve such problem by casting.

+3  A: 

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)
Mark Byers
+1  A: 

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))
allyourcode
@allyourcode: Presumably English is not his native tongue. You're not sure about his wish to join a list of items many of which he is converting to `str`? Please consider the possibility that you need to add some fuzzy logic to your parser ;-)
John Machin
@John I considered that, but if he is good at English, I wanted to gently push him to bring the level of English on SO up to his normal level. I think my answer does entertain various interpretations and situations he might be in.
allyourcode
+1  A: 

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)

Ivo van der Wijk
A: 

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[5]

Tony Veijalainen