Python string concatenation: + operator/join function/format function/f-strings

Python string concatenation: + operator/join function/format function/f-strings
Page content

This time, I will introduce the method of string concatenation in Python. Here, the Python version is assumed to be 3.x.

Concatenate with ‘+’ operator

The simplest way is string concatenation using the + operator. Some programming languages ​​don’t support string concatenation with the + operator, but Python has no problem.

1a = 'aaa'
2b = 'bbb'
3c = 'ccc'
4txt = a + b + c
5print(txt)
6
7> aaabbbccc

Concatenate between string literals

Python allows strings to be concatenated between string literals without using the + operator. However, since I often use strings stored in variables, I have never used this method honestly.

1txt = 'aaa' 'ccc'
2print(txt)
3
4> aaacccc

Join lists with the join () function

Next, concatenate the elements of the string stored in the list. It can be linked with a for statement as follows, but the description will be redundant.

1arr = ['aaa', 'bbb', 'ccc']
2txt = ''
3for t in arr:
4    txt += t
5print(txt)
6
7> aaabbbccc

Now, you can easily join by using the str type join() function.

1arr = ['aaa', 'bbb', 'ccc']
2# String join with empty character
3txt = ''.join(arr)
4print(txt)
5
6> aaabbbccc

In the above example, strings are joined by an empty character (''), but any combination character can be specified. For example, to combine as a string separated by commas, implement as follows.

1arr = ['aaa', 'bbb', 'ccc']
2txt = ','.join(arr)
3print(txt)
4
5> aaa,bbb,ccc

concatenate with format () function

The format() function is for converting the format of a string, but since the final output of this function is a string, it can also be used for concatenation. Variables given as arguments are expanded in order for the occurrence of {} in the template string.

1a = 'aaa'
2b = 'bbb'
3c = 'ccc'
4txt = '{}{}{}'.format(a, b, c)
5print(txt)
6
7> 'aaabbbccc'

By giving a numerical value like {0}, it’s possible to expand variables in any order or to expand variables repeatedly.

1a = 'aaa'
2b = 'bbb'
3c = 'ccc'
4txt = '{0}{2}{1}'.format(a, b, c)
5print(txt)
6
7> 'aaacccbbb'

concatenate with f-strings

In Python 3.6 and above, use f-strings(formatted string literals) which makes the format() function easier to use. This can be used by simply adding a f or F before the quotes in the string literal. Expand any variable in f-strings, and call any process in {}.

1a = 'aaa'
2b = 'bbb'
3c = 'ccc'
4txt = f'{a}{b}{c}'
5print(txt)
6
7> 'aaabbbccc'