0 votes
1 view
in Python by (47.7k 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.

http://www.skymind.com/~ocrow/python_string/

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: 

0.11338996887207031 

a += b: 

0.11040496826171875

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

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


Categories

...