How to Append to a String in Python
To append to a string in Python, you can use the + operator, f-strings, the join() function, or the format() function.
The following examples show how to append to a string in Python using different methods.
Using + Operator
We can use the + operator to append strings in Python.
Suppose we have the following strings:
# Declare strings
string1 = "Hello"
string2 = "world"
# Append strings
string = string1 + " " + string2
# Show appended string
print(string)
Output: 👇️
Hello world
In this example, we use the + operator to concatenate string1 and string2.
Using f-string
We can use f-strings to append strings in Python.
Suppose we have the following string:
# Declare string
string1 = "Hello"
# Append strings
string = f"{string1} world"
# Show appended string
print(string)
Output: 👇️
Hello world
In this example, we use an f-string to concatenate string1 with the string " world".
Using join() Function
We can use the join() function to append strings in Python.
Suppose we have the following string:
# Declare string
string1 = "Hello"
# Append strings
string = ' '.join([string1, "world"])
# Show appended string
print(string)
Output: 👇️
Hello world
In this example, we use the join() function to concatenate string1 with the string " world".
Using format() Function
We can use the format() function to append strings in Python.
Suppose we have the following string:
# Declare string
string1 = "Hello"
# Append strings
string = "{} world".format(string1)
# Show appended string
print(string)
Output: 👇️
Hello world
In this example, we use the format() function to concatenate string1 with the string " world".