How to concatenate two strings in Python

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:

HelloJavaTpoint
Hello JavaTpoint

Explanation:

In the above code, the variable str1 stores the string “Hello” and variable str2 stores the “JavaTpoint”. 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 JavaTpoint

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 JavaTpoint”.

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 JavaTpoint
Hello JavaTpoint

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.


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263614.html

(0)
上一篇 2022年5月30日
下一篇 2022年5月30日

相关推荐

发表回复

登录后才能评论