Home » How to concatenate two strings in Python

How to concatenate two strings in Python

by Online Tutorials Library

How to concatenate two strings in Python

Python string is a collection of Unicode characters. Python provides many built-in functions for string manipulation. String concatenation is a process when one string is merged with another string. It can be done in the following ways.

  • Using + operators
  • Using join() method
  • Using % method
  • Using format() function

Let’s understand the following string concatenation methods.

Using + operator

This is an easy way to combine the two strings. The + operator adds the multiple strings together. Strings must be assigned to the different variables because strings are immutable. Let’s understand the following example.

Example –

Output:

Hello Devansh  

Explanation:

In the above example, the variable str1 stores the string “Hello”, and variable str2 stores the “Devansh”. We used the + operator to combine these two string variables and stored in str3.

Using join() method

The join() method is used to join the string in which the str separator has joined the sequence elements. Let’s understand the following example.

Example –

Output:

Hellotutoraspire  Hello tutoraspire  

Explanation:

In the above code, the variable str1 stores the string “Hello” and variable str2 stores the “tutoraspire”. The join() method returns the combined string that is stored in the str1 and str2. The join() method takes only list as an argument.

Using % Operator

The % operator is used for string formatting. It can also be used for string concatenation. Let’s understand the following example.

Example –

Output:

Hello tutoraspire  

Explanation –

In the above code, the %s represents the string data-type. We passed both variables’s value to the %s that combined the strings and returned the “Hello tutoraspire”.

Using format() function

Python provides the str.format() function, which allows use of multiple substitutions and value formatting. It accepts the positional arguments and concatenates the string through positional formatting. Let’s understand the following example.

Example –

Output:

Hello tutoraspire  Hello tutoraspire  

Explanation:

In the above code, the format() function combines both strings and stores into the str3 variable. The curly braces {} are used as the position of the strings.


You may also like