How to Append to String in Python ?
In Python, Strings are immutable datatypes. So, appending to a string is nothing but string concatenation which means adding a string at the end of another string.
Let us explore how we can append to a String with a simple example in Python.
s = "Geeks" + "ForGeeks"
print(s)
Output
GeeksForGeeks
Note: In the above example, you might note that there is no space between the two strings. For this, you can either add a space in one of the original strings or append a space as well.
s1 = "Geeks"
s2 = "For"
s3 = "Geeks"
print(s1 + " " + s2 + " " +s3)
Output
Geeks For Geeks
Now let us see different ways to append to a String in Python one by one.
Using join() Function
join() function is also used to concatenate or append two or more strings in Python. It takes an iterable that is a list or a tuple as the parameters and join them in the given order.
s1 = "Geeks"
s2 = "For Geeks"
print(" ".join([s1, s2]))
Output
Geeks For Geeks
Using f-String
f-string in Python is used in string formatting. It directly embeds the expression inside the curly braces.
s1 = "Geeks"
s2 = "For Geeks"
print(f"{s1} {s2}")
Output
Geeks For Geeks
Using format() Function
Python format() function is an inbuilt function used to format strings. Unline f-string, it explicitly takes the expression as arguments.
s1 = "Geeks"
s2 = "For Geeks"
print("{} {}".format(s1, s2))
Output
Geeks For Geeks
Using __add__() Method
__add__() method is a Python inbuilt method that is used to define the behaviour of concatenate operator "+" for objects. In this example, we have explicitly added a space in the start of the second string.
s1 = "Geeks"
s2 = "For Geeks"
print(s1.__add__(s2))
Output
GeeksFor Geeks