Skip to content

Python append to string

  • by

Python has multiple ways to append to string in another string to the end. Simple and traditional is the += operator.

Note: In Python, strings are immutable, which means you cannot modify them in place. However, you can concatenate strings using the + operator or by using the += operator to append to a string variable. Here are a few examples:

Python append to a string

Simple example code.

s = "Python "
add_string = "is best"

# adding one string to another
s += add_string

print(s)

Output:

Python append to a string

Join Strings Into a String using join()

s = "Python "
add_string = "is best"

# adding one string to another
res = "".join((s, add_string))

print(res)

Append one string to another using f-string

s = "Python "
add_string = "is best"

# adding one string to another
res = f'{s}{add_string}'

print(res)

Using the __add__ method

s = "Python "
add_string = "is best"

# adding one string to another
res = s.__add__(add_string)

print(res)

Using format() 

s = "Python "
add_string = "is best"

# adding one string to another
res = "{}{}".format(s, add_string)

print(res)

Which is the preferred way to concatenate a string in Python

Answer: The best way of appending a string to a string variable is to use + or +=. This is because it’s readable and fast. They are also just as fast, which one you choose is a matter of taste, the latter one is the most common. Here are the timings with the timeit module:

a = a + b:
0.11338996887207031
a += b:
0.11040496826171875

Source: https://stackoverflow.com/questions/12169839

Do comment if you have any doubts or suggestions on this Python append topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading