Open In App

Python String Concatenation

Last Updated : 05 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

String concatenation in Python allows us to combine two or more strings into one. In this article, we will explore various methods for achieving this. The most simple way to concatenate strings in Python is by using the + operator.

Using + Operator

Using + operator allows us to concatenation or join strings easily.

s1 = "Hello"
s2 = "World"
res = s1 + " " + s2
print(res)

Output
Hello World

Explanation: s1 + ” ” + s2 combines s1 and s2 with a space between them.

Note: This method is less efficient when combining multiple strings repeatedly.

Let’s explore other different method for string concatenation in string:

Using join() Method for Concatenation

Use join() function to concatenate strings with a specific separator. It’s especially useful when working with a sequence of strings, like a list or tuple. If no separator is needed then simply use join() with an empty string.

a = ["Python", "is", "a", "popular", "language", "for", "programming"]

# Use join() method to concatenate list elements
# into a single string, separated by spaces
res = " ".join(a)
print(res)

Output
Python is a popular language for programming

Explanation: ” “.join() method combines each element in words with a space between them.

Note: join() is optimal for large-scale string concatenation since it minimizes the creation of intermediate strings.

Using format() Method

The format() method provided an easy way to combine and format strings. It is very helpful when we want to include multiple variables or values. By using curly braces {} in a string, we can create placeholders that format() will fill in with the values we’ll provide.

s1 = "Python"
s2 = "programming"

# Use format() method to create a new string that includes both variables
res = "{} is a popular language for {}".format(s1, s2)

print(res)

Output
Python is a popular language for programming

Explanation: {} placeholders in the string are replaced by the values inside format().

Using f-strings (Formatted Strings)

F-strings make it easy to combine and format strings in Python. By adding an f before the string, we can directly include variables in curly braces {}.

s1 = "Python"
s2 = "programming"

# Use an f-string to create a formatted string
# that includes both variables
res = f"{s1} is a popular language for {s2}"

print(res)

Output
Python is a popular language for programming

Explanation: The f before the string allows us to use expressions inside curly braces {}.

Which method to choose?

  • + Operator: Simple and readable but not ideal for multiple concatenations in loops.
  • join() Method: Highly efficient for concatenating lists of strings.
  • f-strings: Use when variables are involved.
  • format(): Similar to f-strings but compatible with earlier versions.



Next Article

Similar Reads

three90RightbarBannerImg