Concatenating and joining strings in Python: + operators, join functions, etc.

Money and Business

The following is a description of how to concatenate and join string str in Python.

  • Concatenating and merging multiple strings: +,+=operator
  • Concatenate and combine numbers and strings: +,+=operator,str(),format(),f-string
  • Concatenate and combine lists (arrays) of strings into a single string:join()
  • Concatenate and combine lists (arrays) of numbers into a single string:join(),str()

Concatenating and merging multiple strings: +, +=operator

connection: +operator

The ++ operator can be used to concatenate the following string literals and string variables

  • '…'
  • “…”
s = 'aaa' + 'bbb' + 'ccc'
print(s)
# aaabbbccc

s1 = 'aaa'
s2 = 'bbb'
s3 = 'ccc'

s = s1 + s2 + s3
print(s)
# aaabbbccc

s = s1 + s2 + s3 + 'ddd'
print(s)
# aaabbbcccddd

connection: +=operator

The += operator, a cumulative assignment operator, can also be used. The string variable on the left-hand side is concatenated with the string on the right-hand side, and is assigned and updated.

s1 += s2
print(s1)
# aaabbb

If you want to add a string to the end of a string variable, simply process the string variable and any string literal (or another string variable) with the += operator.

s = 'aaa'

s += 'xxx'
print(s)
# aaaxxx

Consecutive concatenation of string literals

If you simply write string literals side by side, the string literals will be concatenated.

s = 'aaa''bbb''ccc'
print(s)
# aaabbbccc

It is acceptable to have a space between two lines or a backslash line break (considered a continuation).

s = 'aaa'  'bbb'    'ccc'
print(s)
# aaabbbccc

s = 'aaa'\
    'bbb'\
    'ccc'
print(s)
# aaabbbccc

There is a technique to use this to write long strings on multiple lines in the code.

This writing method is not possible for string variables.

# s = s1 s2 s3
# SyntaxError: invalid syntax

Numeric and string concatenation/concatenation: +,+=operator,str(),format(),f-string

A + operation of a different type results in an error.

s1 = 'aaa'
s2 = 'bbb'

i = 100
f = 0.25

# s = s1 + i
# TypeError: must be str, not int

If you want to concatenate a numeric value (e.g., integer type int or floating-point type float) with a string, convert the numeric value to a string type with str() and then concatenate them with the + operator (or += operator).

s = s1 + '_' + str(i) + '_' + s2 + '_' + str(f)
print(s)
# aaa_100_bbb_0.25

If you want to convert the format of a number, such as zero-filling or decimal places, use the format() function or the string method format().

s = s1 + '_' + format(i, '05') + '_' + s2 + '_' + format(f, '.5f')
print(s)
# aaa_00100_bbb_0.25000

s = '{}_{:05}_{}_{:.5f}'.format(s1, i, s2, f)
print(s)
# aaa_00100_bbb_0.25000

Of course, it is also possible to embed the value of a variable directly in a string without formatting. This is simpler to write than using the + operator.

s = '{}_{}_{}_{}'.format(s1, i, s2, f)
print(s)
# aaa_100_bbb_0.25

See the following article for details on how to specify the format.

Since Python 3.6, a mechanism called f-strings (f-string) has also been introduced, which is even simpler to write than format().

s = f'{s1}_{i:05}_{s2}_{f:.5f}'
print(s)
# aaa_00100_bbb_0.25000

s = f'{s1}_{i}_{s2}_{f}'
print(s)
# aaa_100_bbb_0.25

Concatenate and join lists (arrays) of strings: join()

The string method join() can be used to concatenate a list of strings into a single string.

The following is how to write it.

'String to be inserted between'.join([List of strings to be concatenated])

Call join() method with 'string to insert between' and pass [list of strings to concatenate] as an argument.

If an empty string is used, [list of strings to be concatenated] will be simply concatenated, if a comma is used, the strings will be comma-separated, and if a newline character is used, each string element will be newlined.

l = ['aaa', 'bbb', 'ccc']

s = ''.join(l)
print(s)
# aaabbbccc

s = ','.join(l)
print(s)
# aaa,bbb,ccc

s = '-'.join(l)
print(s)
# aaa-bbb-ccc

s = '\n'.join(l)
print(s)
# aaa
# bbb
# ccc

Although only an example of a list is given here, other iterable objects such as tuples can be specified as arguments to join() as well.

In contrast to join(), split() is used to split a string delimited by a specific delimiter and obtain it as a list.

Concatenate and combine lists (arrays) of numbers as strings: join(),str()

An error occurs if the argument to join() is a list whose elements are not strings.

l = [0, 1, 2]

# s = '-'.join(l)
# TypeError: sequence item 0: expected str instance, int found

To concatenate a list of numbers into a single string, apply the str() function to each element in the list comprehension notation to convert the numbers into a string, and then join them with join().

s = '-'.join([str(n) for n in l])
print(s)
# 0-1-2

It can also be written as a generator expression, which is a generator version of list comprehensions. Generator expressions are enclosed in parentheses, but the parentheses can be omitted if the generator expression is the only argument to a function or method.

s = '-'.join((str(n) for n in l))
print(s)
# 0-1-2

s = '-'.join(str(n) for n in l)
print(s)
# 0-1-2

Generator expressions generally have the advantage of using less memory than list comprehensions, but there is no particular advantage to using generator expressions since join() converts generators to lists in its internal processing. In fact, it is slightly faster to use list comprehensions from the beginning.

For more information on list comprehensions and generator expressions, see the following article.

Copied title and URL