What is the best way to concatenate strings in python?

The best way of appending a string to a string variable is to use + or +=. 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

However, those who recommend having lists and appending to them and then joining those lists, do so because appending a string to a list is presumably very fast compared to extending a string. And this can be true, in some cases. Here, for example, is one million appends of a one-character string, first to a string, then to a list:

a += b:
0.10780501365661621
a.append[b]:
0.1123361587524414

OK, turns out that even when the resulting string is a million characters long, appending was still faster.

Now let's try with appending a thousand character long string a hundred thousand times:

a += b:
0.41823482513427734
a.append[b]:
0.010656118392944336

The end string, therefore, ends up being about 100MB long. That was pretty slow, appending to a list was much faster. That that timing doesn't include the final a.join[]. So how long would that take?

a.join[a]:
0.43739795684814453

Oups. Turns out even in this case, append/join is slower.

So where does this recommendation come from? Python 2?

a += b:
0.165287017822
a.append[b]:
0.0132720470428
a.join[a]:
0.114929914474

Well, append/join is marginally faster there if you are using extremely long strings [which you usually aren't, what would you have a string that's 100MB in memory?]

But the real clincher is Python 2.3. Where I won't even show you the timings, because it's so slow that it hasn't finished yet. These tests suddenly take minutes. Except for the append/join, which is just as fast as under later Pythons.

Yup. String concatenation was very slow in Python back in the stone age. But on 2.4 it isn't anymore [or at least Python 2.4.7], so the recommendation to use append/join became outdated in 2008, when Python 2.3 stopped being updated, and you should have stopped using it. :-]

[Update: Turns out when I did the testing more carefully that using + and += is faster for two strings on Python 2.3 as well. The recommendation to use ''.join[] must be a misunderstanding]

However, this is CPython. Other implementations may have other concerns. And this is just yet another reason why premature optimization is the root of all evil. Don't use a technique that's supposed "faster" unless you first measure it.

Therefore the "best" version to do string concatenation is to use + or +=. And if that turns out to be slow for you, which is pretty unlikely, then do something else.

So why do I use a lot of append/join in my code? Because sometimes it's actually clearer. Especially when whatever you should concatenate together should be separated by spaces or commas or newlines.

Summary: in this tutorial, you’ll learn various ways to concatenate strings in Python.

Python provides you with various ways to concatenate one or more strings into a new string.

Since Python string is immutable, the concatenation always results in a new string.

1] Concatenating literal strings

To concatenate two or more literal strings, you just need to place them next to each other. For example:

s = 'String' ' Concatenation' print[s]

Code language: PHP [php]

Output:

String Concatenation

Code language: JavaScript [javascript]

Note that this way won’t work for the string variables.

2] Concatenating strings using the + operator

A straightforward way to concatenate multiple strings into one is to use the + operator:

s = 'String' + ' Concatenation' print[s]

Code language: PHP [php]

And the + operator works for both literal strings and string variables. For example:

s1 = 'String' s2 = s1 + ' Concatenation' print[s2]

Code language: PHP [php]

Output:

String Concatenation

Code language: JavaScript [javascript]

3] Concatenating strings using the += operator

Similar to the + operator, you can use the += operator to concatenate multiple strings into one:

s = 'String' s += ' Concatenation' print[s]

Code language: PHP [php]

Output:

String Concatenation

Code language: JavaScript [javascript]

4] Concatenating strings using the join[] method

The join[] method allows you to concatenate a list of strings into a single string:

s1 = 'String' s2 = 'Concatenation' s3 = ''.join[[s1, s2]] print[s3]

Code language: PHP [php]

Output:

StringConcatenation

The join[] method also allows you to specify a delimiter when concatenating strings. For example:

s1 = 'String' s2 = 'Concatenation' s3 = ' '.join[[s1, s2]] print[s3]

Code language: PHP [php]

Output:

String Concatenation

Code language: JavaScript [javascript]

In this example, we use the join[] method to concatenate strings delimited by a space.

The following example use the join[] method to concatenate strings delimited by a comma:

s1, s2, s3 = 'Python', 'String', 'Concatenation' s = ','.join[[s1, s2, s3]] print[s]

Code language: PHP [php]

Output:

Python,String,Concatenation

Code language: JavaScript [javascript]

5] Concatenating strings using the %-formatting

String objects have the built-in % operator that allows you to format strings. Also, you can use it to concatenate strings. For example:

s1, s2, s3 = 'Python', 'String', 'Concatenation' s = '%s %s %s' % [s1, s2, s3] print[s]

Code language: PHP [php]

Output:

Python String Concatenation

Code language: JavaScript [javascript]

In this example, Python substitutes a %s in the literal string by corresponding string variable in the tuple that follows the % operator.

6] Concatenating strings using the format[] method

You can use the format[] method to concatenate multiple strings into a string. For example:

s1, s2, s3 = 'Python', 'String', 'Concatenation' s = '{} {} {}'.format[s1, s2, s3] print[s]

Code language: PHP [php]

Output:

Python String Concatenation

Code language: JavaScript [javascript]

In this example, you use the {} in the string literal and pass the string that you want to concatenate to the format[] method. The format[] method substitutes the {} by the corresponding string argument.

7] Concatenating strings using f-strings

Python 3.6 introduced the f-strings that allow you to format strings in a more concise and elegant way.

And you can use the f-strings to concatenate multiple strings into one. For example:

s1, s2, s3 = 'Python', 'String', 'Concatenation' s = f'{s1} {s2} {s3}' print[s]

Code language: PHP [php]

Output:

Python String Concatenation

Code language: JavaScript [javascript]

Which method should you use to concatenate strings

Even though there’re multiple ways to concatenate strings in Python, it’s recommended to use the join[] method, the + operator, and f-strings to concatenate strings.

Did you find this tutorial helpful ?

What is the most efficient way to concatenate many strings together Python?

Practical Data Science using Python The best way of appending a string to a string variable is to use + or +=. This is because it's readable and fast. They are also just as fast.

How do you concatenate strings 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.

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + [String concatenation] operator. By concat[] method.

What are the different ways of concatenating data in Python?

We can perform string concatenation using following ways:.
Using + operator..
Using join[] method..
Using % operator..
Using format[] function..
Using f-string [Literal String Interpolation].

Chủ Đề