w3resource

How do you concatenate strings in Python?

Exploring string concatenation methods in Python

In Python, you can concatenate (combine) strings using various methods. Here are some common methods for string concatenation:

Using the + operator:

The + operator can be used to concatenate two or more strings together.

Code:

str1 = "Good "
str2 = "Morning!"
result = str1 + str2
print(result)

Output:

Good Morning!

Using the += operator:

The += operator can be used to concatenate and update the value of an existing string.

Code:

str1 = "Good "
str2 = "Morning!"
str1 += str2
print(str1)

Output:

Good Morning!

Using the join() method:

The join() method is used to concatenate a list of strings into a single string. The function takes an iterable (e.g., list, tuple) as an argument and joins its elements with the calling string.

Code:

words = ["Red", "Green", "Orange"]
separator = ", "
result = separator.join(words)
print(result)  

Output:

Red, Green, Orange

Using f-strings (formatted string literals):

In Python 3.6 and later versions, F-strings provide a convenient way to concatenate strings with variable values.

Code:

name = "Mango"
ctr = 10
result = f"There are {ctr} {name}es in a basket."
print(result)

Output:

There are 10 Mangoes in a basket.

Using parentheses for line continuation:

Parentheses can be used to concatenate strings over multiple lines if we have a long string or want to break it into multiple lines for better readability.

Code:

long_str = ("The long-string instrument is a musical instrument in which the "
            "string is of such a length that the fundamental transverse wave " 
            "is below what a person can hear as a tone. If the tension and "
            "the length result in sounds with such a frequency, the "
            "tone becomes a beating frequency that ranges from a short reverb"
            "(approx 5-10 meters) to longer echo sounds (longer than 10 meters.")
print(long_str)

Output:

The long-string instrument is a musical instrument in which the string is of such a length that the fundamental transverse wave is below what a person can hear as a tone. If the tension and the length result in sounds with such a frequency, the tone becomes a beating frequency that ranges from a short reverb(approx 5-10 meters) to longer echo sounds (longer than 10 meters.

Note:

All of these methods achieve the same result by combining strings. It depends on the context and the number of strings involved in the concatenation whether they are more or less suitable.



Follow us on Facebook and Twitter for latest update.