Python Concatenate Strings (plus operator, join, f-string, itertools.repeat)

In Python, strings can be concatenated with plus symbols like common arithmetic calculations.

a = 'Apple'
b = 'Book'

c = a + b

# AppleBook

"+=" operator

a = 'apple'
b = 'banana'

a += b

print(a)  # applebanana
print(b)  # banana

"+=" is a common operator in programming languages. In Python, an id, which is a kind of an object address, of a string has changed after added. So the original string and updated string are essentially different.

a = 'apple'
b = 'banana'

print(id(a))  # 4637695088

a += b

print(id(a))  # 4637695344

Join strings with something

To concatenate words with a hyphen, make a list of those strings and use join(). The function is a string method not a list method. So write the . after the delimiter.

a = 'Apple'
b = 'Book'
c = 'Cake'

d = '-'.join([a, b, c])

# Apple-Book-Cake

In this case, - is a delimiter and the join() is its method.

Python f-strings

a = 'apple'
b = 'banana'

c = f'{a}{b}'
d = f'{a} : {b}'

print(c)  # applebanana
print(d)  # apple : banana

As explained in the f-strings post, a string that starts with f can contain variables. It can be used when concatenating strings.

Repeat strings

import itertools

r = itertools.repeat('ABC', 4)

s = ''.join(r)

print(s)  # ABCABCABCABC

The itertools.repeat() returns an iterable (a repeat object) producing the string many times.


Powered by Markdown