Scripting

How to Add Strings in Python

How_to_Add_Strings_in_Python

A string is a text consisting of a sequence of different characters that can be combined with other strings. For adding strings in Python, we have the following methods:

  1. By using the + operator
  2. By using the join function
  3. By using the format function
  4. How to Add Strings by using the + operator

In python + operator is used for the concatenation of two or more strings.

A = 'I am string one'

B = 'I am string two'

C= A + B

print(C)

Text Description automatically generated

Figure 1: By using the + operator

Output:

Figure 2: Output

In Figure 1, we have two strings, A and B. We have added A and B strings using the + operator and created a new string C in Figure 2.

How to Add Strings by Using the Join Function

The join function combines all the strings in the list, and here we have the joining character space between elements.

A = ' one '

B = ' two '

C = ' three '

D = ' four '

E= ''.join([A, B, C, D])

print(E)

Text Description automatically generated

Figure 3: By using the join function

Output:

Figure 4: Output

In figure 3 we have added four strings A, B, C, and D using the join function and placed space as a joining character between elements to create a new string E in figure 4.

How to Add Strings by Using the Format Function

This is a string method used for various substitutions and value formatting, and it also concatenates elements of a string.

A = 'one'

B = 'two'

C = 'three'

D= '{} {} {}'.format(A, B, C)

print(D)

Text Description automatically generated with medium confidence

Figure 5: By using the format function

Output:

Figure 6: Output

In Figure 5, we have added three strings, A, B, and C, using the format function where curly braces {} define the position of strings. So, all strings A, B, and C are placed in their respective curly braces and create a new string D in figure 6.

Similar Posts