Python - How does string concatenation in a for loop?

I need to "concatenate a string in a for loop". To explain, I have this list:

list = ['first', 'second', 'other'] 

And inside the for loop, I need to end up with this:

 endstring = 'firstsecondother' 

Can you let me know how to do this in python?

+6
source share
5 answers

This is not how you do it.

 >>> ''.join(['first', 'second', 'other']) 'firstsecondother' 

- Is this what you want.

If you do this in a for loop, it will be inefficient, as the add / concatenation line does not scale well (but of course it is possible):

 >>> mylist = ['first', 'second', 'other'] >>> s = "" >>> for item in mylist: ... s += item ... >>> s 'firstsecondother' 
+27
source
 endstring = '' for s in list: endstring += s 
+5
source

If you need, you can do this in a for loop:

 mylist = ['first', 'second', 'other'] endstring = '' for s in mylist: endstring += s 

but you should use join() :

 ''.join(mylist) 
+2
source

This should work:

 endstring = ''.join(list) 
+1
source

While .join is more pythonic and the correct answer for this problem, it is indeed possible to use a for loop.

If this is homework (add a tag, if so!), And you should use a for loop, then that will work (although it is not pythonic, and in fact it should not be done that way if you are a professional python writer ):

 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 “prints”, I just threw them there so you can see what is happening.

0
source

Source: https://habr.com/ru/post/902255/


All Articles