note.nkmk.me

Concatenate strings in Python (+ operator, join, etc.)

Posted: 2020-02-04 / Tags: Python, String

How to concatenate strings in Python is explained below with the sample code.

  • Concatenate multiple strings: + operator, += operator
  • Concatenate strings and numbers: + operator, += operator, str(), format()
  • Concatenate a list of strings into one string: join()
  • Concatenate a list of numbers into one string: join(), str()
Sponsored Link

Concatenate multiple strings: + operator, += operator

+ operator

You can use the + operator to concatenate string literals ('...' or "...") 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

+= operator

The in-place operator += can also be used.

The string on the right is concatenated after the string variable on the left.

s1 += s2
print(s1)
# aaabbb

If you want to add a string to the end of a string variable, use the += operator.

s = 'aaa'

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

Concatenate by writing string literals consecutively

If you write string literals consecutively, they are concatenated.

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

If there are multiple spaces or newlines with backslash \ (considered as continuation lines) between the strings, they are concatenated as well.

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

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

By using this, you can write long strings on multiple lines in the code.

You can't do this for string variables.

# s = s1 s2 s3
# SyntaxError: invalid syntax

Concatenate strings and numbers: + operator, += operator, str(), format()

Different types of + operations raise 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 number, such as an integer int or a floating point float, with a string, convert the number to a string with str() and then use the + operator or += operator.

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

Use the format() function or the string method format() if you want to convert the number format, such as zero padding or decimal places.

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
Sponsored Link

Concatenate a list of strings into one string: join()

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

Write as follows:

'String to insert'.join([List of strings])

Call join() method from 'String to insert' and pass [List of strings].

If you use an empty string '', [List of strings] is simply concatenated, and if you use a comma ,, it is a comma-delimited string. If a newline character \n is used, a newline will be inserted for each string.

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

Note that only an example of a list has been described here, but other iterable objects such as tuples can be similarly specified as arguments of join().

Use split() to split a string separated by a specific delimiter and get it as a list. See the following post for details.

Concatenate a list of numbers into one string: join(), str()

If you set a non-string list to join(), an error will occur.

l = [0, 1, 2]

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

If you want to concatenate a list of numbers into a single string, apply the str() function to each element in the list comprehension to convert numbers to strings, then concatenate them with join().

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

It can be written as a generator expression, which is a generator version of list comprehensions. Generator expressions are enclosed in parentheses (), but you can omit () if the generator expression is the only argument of 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

In general, generator expressions have an advantage that the memory usage is reduced as compared with the list comprehension. However, since join() internally converts a generator into a list, there is no advantage to using generator expressions.

See the following post for details on list comprehensions and generator expressions.

Sponsored Link
Share

Related Categories

Related Posts