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?
To concatenate strings we will use for loop, and the “+ ” operator is the most common way to concatenate strings 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.
Two strings can be concatenated in Python by simply using the '+' operator between them. More than two strings can be concatenated using '+' operator.
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.
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'
endstring = ''
for s in list:
endstring += s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With