Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to concatenate to a string in a for loop? [duplicate]

Tags:

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?

like image 468
André Avatar asked Nov 23 '11 21:11

André


People also ask

How do you combine strings in a for loop in Python?

To concatenate strings we will use for loop, and the “+ ” operator is the most common way to concatenate strings in python.

How do you concatenate a string multiple times in Python?

In Python, you can concatenate two different strings together and also the same string to itself multiple times using + and the * operator respectively.

How do you concatenate strings to a string in Python?

Two strings can be concatenated in Python by simply using the '+' operator between them. More than two strings can be concatenated using '+' operator.

How do you concatenate in a loop?

str1 = str2 + str2; Since Strings are immutable in java, instead of modifying str1 a new (intermediate) String object is created with the concatenated value and it is assigned to the reference str1. If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool.


2 Answers

That's not how you do it.

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

is what you want.

If you do it in a for loop, it's going to be inefficient as string "addition"/concatenation doesn't scale well (but of course it's possible):

>>> mylist = ['first', 'second', 'other']
>>> s = ""
>>> for item in mylist:
...    s += item
...
>>> s
'firstsecondother'
like image 136
Tim Pietzcker Avatar answered Oct 20 '22 19:10

Tim Pietzcker


endstring = ''
for s in list:
    endstring += s
like image 26
Samuel Edwin Ward Avatar answered Oct 20 '22 21:10

Samuel Edwin Ward