0 votes
1 view
in Python by (47.8k points)

Since Python's string can't be changed, I was wondering how to concatenate a string more efficiently?

I can write like it:

s += stringfromelsewhere

or like this:

s = [] s.append(somestring) 

later s = ''.join(s)

While writing this question, I found a good article talking about the topic.


But it's in Python 2.x., so the question would be did something change in Python 3?

1 Answer

0 votes
by (107k points)
edited by

You should use + or += for appending the string. This is because it's readable and fast. They are also just as fast, which one you choose is a matter of taste, the latter one is the most common. Here are timings with the timeit module:

a = a + b: 


a += b: 


To know more about this you can have a look at the following video tutorial:-

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !