How to concatenate strings in Python

“Data is the new oil, and strings are its rich deposits.”—British mathematician Clive Humby coined the first phrase; the latter part is a popular addition circulating in the tech industry without clear attribution.

Key takeaways:

  • Concatenation: Concatenation combines multiple elements into a single, meaningful string, essential for tasks like generative AI, creating URLs and file paths, and generating personalized messages based on user input.

  • Methods for concatenation: Python provides various methods for string concatenation, each suited for different scenarios:

    • Operator (+): Directly joins two strings, perfect for straightforward concatenation.

    • Operator (%): Offers a way to format and combine strings using placeholders.

    • Method (join()): Efficiently combines lists of strings with or without separators, ideal for batch operations.

    • Method (format()): Uses curly braces {} for placing variables within strings, enhancing readability.

    • Comma (,): Concatenates strings with a space, useful for quick and clean outputs.

    • Strings (f) (Introduced in Python 3.6): These provide a readable and concise way to embed expressions inside string literals.

    • Operator (*): Repeats a string multiple times, useful for generating repeated patterns.

    • Loop with (+=): Builds strings from a list in a specified order, offering flexibility in dynamic concatenation tasks.

  • Selecting the right method based on context can improve code readability and performance, making string manipulation more efficient and effective.

What do Generative AI, website generators, and error alerts share? They merge strings to form meaningful text. String concatenation is a fundamental operation in many programming languages that combines two or more strings into a single string. It is difficult to think of a domain that doesn’t require string concatenation in one of its steps—web development, data science, and user interface development, naming just a few, wouldn't be possible without it. Several applications rely on concatenating strings:

  • Creating file paths: Merging the name of the file path with its file name.

  • Personalized content: Creating customize messages or alerts based on the user input.

  • URL construction: Creating URLs based on the dynamic parameters and user input.

  • Natural language processing: Constructing sentences or phrases from individual words.

  • Bioinformatics: Joining DNA or protein sequences for comparison and analysis.

Python string concatenation

Guido van Rossum highlights the importance of readability and simplicity in Python’s design. The following eight-string concatenation methods exemplify his perspective by providing an intuitive and straightforward way to concatenate strings.

  • Using + operator
  • Using % operator
  • Using join() method
  • Using format() function
  • Using , comma
  • Using f-string
  • Using * operator
  • Using loop and += operator

Note: Most of these string merging methods in Python programming implicitly convert nonstring types into strings (for example %, format(), f-strings, print() with commas). However, methods such as +, *, and += require explicit conversion to strings when non-string types are involved.

1. Concatenate strings using + operator

The + operator is the simplest string operation to concatenate two different strings. This operator only allows the concatenation of elements with a string data type. Otherwise, it will throw a TypeError. The following illustration shows how it is done:

Concatenate strings using + operator
1 of 3

Let’s see the code implementation of string concatenation using + operator:

str1="Hello"
str2="World"
print ("String 1:",str1)
print ("String 2:",str2)
str=str1+str2
print("Concatenated two different strings:",str)

2. Concatenate strings using % operator

The % operator is used for Python string formatting that includes placeholders, but it can also be used for concatenating strings. Let’s see how to perform string concatenation using % operator.

str1 = "Welcome"
str2 = "to"
str3 = "Educative"
print("Platform: % s % s % s" % (str1, str2, str3))

3. Concatenate strings using join() method

The join() function in Python joins the list of strings with or without a separator. It is useful to join Python list of strings into a single string. Let's see a code example for string joining using join() method.

str1 = "Welcome"
str2 = "to"
str3 = "Educative"
# join() method is used to combine the strings without a seperator
print("".join([str1, str2, str3]))
# join() method is used to combine the string with a separator
print(" ".join([str1, str2, str3]))
# join() method is used to combine the list of string with a separator
str_list = ['Welcome', 'to', 'Educative']
print(' '.join(str_list))

4. Concatenate strings using format() method

The format() is another way to concatenate strings. For this purpose, curly braces {} are used as placeholders in the string; the values given in the method's arguments are substituted for them through the format() method. Let's see the code implementation of string concatenation using format() method:

str1 = "Welcome"
str2 = "to"
str3 = "Educative"
print("{} {} {}".format(str1, str2, str3))

5. Concatenate strings using , comma

The , is used when we want to concatenate strings with a single whitespace between them. It is good alternative to + operator. Let's see how to use , for string concatenation

str1 = "Welcome"
str2 = "to"
str3 = "Educative"
print(str1, str2, str3)

6. Concatenate strings using f-string

An f-string is a string literal that is prefixed with the letter f. Inside this string, we can substitute values inside curly braces {}. These values are evaluated at runtime and formatted using the format specifier we provide.

f-strings were introduced in Python 3.6.

str1 = "Welcome"
str2 = "to"
str3 = "Educative"
# String concatenation using f-string
result = f"Platform: {str1} {str2} {str3}."
print(result)

7. Concatenate strings using * operator

Appending the same string to a string can be done using the * operator, as follows:

str=str * n
Python append string n times to itself
  • Where n is the number of times string str is concatenate to itself.

The following illustration shows how it is done:

Concatenate strings using * operator
1 of 3
str1="Hello"
print ("String 1:",str1)
str1=str1*3
print("Concatenated same string:",str1)

8. Concatenate strings using loop and += operator

To concatenate strings in the given order, we will use Python for loop and += operator. The following code concatenates strings from a list (str_list) in a specific order defined by another list of indexes (str_list_order).

str_list = ["How", "Python", "strings", "concatenate", "to", "in"]
# Defining list order
str_list_order = [0, 4, 3, 2, 5, 1]
output_string = ''
for index in str_list_order:
# concatenation using +=
output_string += str_list[index]
# printing result
print("Concatenated strings in given order : " + str(output_string))

Test yourself!

1

Which method was introduced in Python 3.6 for string formatting?

A)

format()

B)

% operator

C)

f-strings

D)

join

Question 1 of 30 attempted

In summary, Python offers a diverse range of methods to concatenate strings, each catering to different needs and preferences. Whether we use the + operator for simple cases, the join() method for efficient list concatenation, or f-strings for formatted output, understanding these methods improves our ability to effectively manage and manipulate strings.

If you're eager to deepen your understanding of Python and sharpen your problem-solving skills,  Become a Python Developer path is the perfect next step. With this structured path, you'll go beyond fundamental concepts like generators and dive into advanced topics that will prepare you for a successful career in software engineering.

Don’t just learn Python—become proficient and ready for the challenges of the real world.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the string concatenation operator in Python?

The + operator is commonly used to join two or more strings to form a single string.


Can we concatenate three strings in Python?

Yes, we can concatenate three strings in Python using various methods. Here are some common ways to concatenate three strings:

str1 = "Welcome"
str2 = "to"
str3 = "Educative"

# Using + operator
str=str1+str2+str3

# Using join() method
print(" ".join([str1, str2, str3]))


Is there a way to concatenate strings with a specific separator?

Yes, we can use the join() method to concatenate strings with any separator, such as a space, comma, asterisk, or dash.

str_list = ['Welcome', 'to', 'Educative']
print('*'.join(str_list))

What is the string replication?

String replication is the process of replicating the same string. We can replicate the string using * operator.

str=str * n

Here str is the string to replicate and n is the number of times we want to replicate the string.


Python concatenate string and int

We can concatenate string and integer by converting the integer to string first. To convert an integer to a string we can use the str() function. For example, "Teams: " + str(5) results in "Teams: 5".


How can we concatenate two strings in Python with space?

There are multiple ways to concatenate two strings in Python with space. Here’s the simplest way with the + operator:

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)

How can we concatenate string and variable in Python?

The + operator in Python can join a string and a variable. However, the variable needs to be a string; if it isn’t, change it using the str() function.


How do you concatenate string lines in Python?

There are multiple methods to concatenate string lines. For example, using + operator, % operator, join() method, format() function, etc. Here’s the code example for concatenating string lines:

str1 = "Welcome to Educative."
str2 = "Find the Right Answer Every Time."
str3 = "Educative Answers is a free web encyclopedia written by devs for devs."

print(str1, str2, str3)

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved