21
How to append a string in Python?
ItsMyCode |
In this tutorial, we will see different ways to append a string in Python. The most efficient methods are using the += operator , join() function, and f-strings.
We know that strings are immutable in Python, which means we cannot change the string variable’s value once it’s declared and assigned. However, we can always return a new string.
We will take a look at 3 different ways to append a string in Python.
- Using
+=
operator - Using
string.join()
method - Using Python
f-strings
The +=
(plus equal) operator is similar to any other language that concatenates two strings and returns a new string in Python without changing the original string.
# Python program to append to a string using += operator
first_name="Bing"
last_name=" Chandler"
# printing first name
print("The first name is: " + str(first_name))
# printing last name
print("The last name is: " + str(last_name))
# Using += operator adding one string to another
first_name += last_name
# print concatenated string
print("The concatenated string is: " + first_name)
Output
The first name is: Bing
The last name is: Chandler
The concatenated string is: Bing Chandler
Another way to append strings in Python is using the join()
method. It has an advantage over the +=
operator as it can append multiple strings or a list of strings.
In this example, we pass a list of strings to the join()
function, which concatenates them together and returns to the output string.
# Python program to append a string using join() function
first_name="Bing"
last_name=" Chandler"
# printing first name
print("The first name is: " + str(first_name))
# printing last name
print("The last name is: " + str(last_name))
# Using join() method to append a string
result= "".join([first_name,last_name])
# print concatenated string
print("The concatenated string is: " + result)
Output
The first name is: Bing
The last name is: Chandler
The concatenated string is: Bing Chandler
If you use Python 3.6 and above version, you can leverage f-strings in Python to append a string.
# Python program to append a string using f-string
first_name="Bing"
last_name=" Chandler"
# printing first name
print("The first name is: " + str(first_name))
# printing last name
print("The last name is: " + str(last_name))
# Using f-string to append a string
result= f"{first_name}{last_name}"
# print concatenated string
print("The concatenated string is: " + result)
Output
The first name is: Bing
The last name is: Chandler
The concatenated string is: Bing Chandler
The post How to append a string in Python? appeared first on ItsMyCode.
21