I need to "concatenate to a string in a for loop". To explain, I have this list:
list = ['first', 'second', 'other']
And inside a for loop I need to end with this:
endstring = 'firstsecondother'
Can you give me a clue on how to achieve this in python?
This question is related to
python
for-loop
concatenation
While "".join is more pythonic, and the correct answer for this problem, it is indeed possible to use a for loop.
If this is a homework assignment (please add a tag if this is so!), and you are required to use a for loop then what will work (although is not pythonic, and shouldn't really be done this way if you are a professional programmer writing python) is this:
endstring = ""
mylist = ['first', 'second', 'other']
for word in mylist:
print "This is the word I am adding: " + word
endstring = endstring + word
print "This is the answer I get: " + endstring
You don't need the 'prints', I just threw them in there so you can see what is happening.
This should work:
endstring = ''.join(list)
If you must, this is how you can do it in a for loop:
mylist = ['first', 'second', 'other']
endstring = ''
for s in mylist:
endstring += s
but you should consider using join()
:
''.join(mylist)
endstring = ''
for s in list:
endstring += s
Source: Stackoverflow.com