How to Add to a String in Python
To add to a string in Python, you can use the concatenation operator +, f-strings, the format() function, or the join() function.
The following examples show how to add to a string in Python using different methods.
Using String Concatenation
We can use the + operator to add to a string in Python.
Suppose we have the following strings:
# Declare strings
first_name = "John"
last_name = "Doe"
# Add strings
full_name = first_name + " " + last_name
# Show concatenated string
print(full_name)
Output: 👇️
John Doe
In this example, we use the + operator to concatenate first_name and last_name.
Using f-string
We can use f-strings to add to a string in Python.
Suppose we have the following string:
# Declare string
first_name = "John"
# Add string
full_name = f"{first_name} Doe"
# Show concatenated string
print(full_name)
Output: 👇️
John Doe
In this example, we use an f-string to concatenate first_name with the string " Doe".
Using join() Function
We can use the join() function to add to a string in Python.
Suppose we have the following strings:
# Declare strings
strings = ["John", " ", "Doe"]
# Add strings
full_name = ''.join(strings)
# Show concatenated string
print(full_name)
Output: 👇️
John Doe
In this example, we use the join() function to concatenate the elements of the list strings.
Using format() Function
We can use the format() function to add to a string in Python.
Suppose we have the following string:
# Declare string
strings = "John"
# Add string
full_name = "{} Doe".format(strings)
# Show concatenated string
print(full_name)
Output: 👇️
John Doe
In this example, we use the format() function to concatenate strings with the string " Doe".