Here are four ways to append a string in Python:
- Using + operator
- Using string.join()
- Using f-string
- Using string.format()
Method 1: Using + operator
The + operator allows you to concatenate or join two strings.
first_name = "Millie"
last_name = "Brown"
# printing first_name string
print("The first name: " + str(first_name))
# printing last_name string
print("The middle name : " + str(last_name))
# Using + operator adding one string to another
final_name = first_name + last_name
# print result
print("The appended string is: " + final_name)
Output
The first name: Millie
The middle name : Brown
The appended string is: MillieBrown
Appending a string multiple times
To append a string multiple times, use the while loop with the += operator. Then, create a user-defined function to append the string n times to the original string.
str = 'Millie'
def string_append(s, n):
op = ''
i = 0
while i < n:
op += s + '-'
i = i + 1
return op
jstring = string_append(str, 5)
print(jstring)
Output
Millie-Millie-Millie-Millie-Millie-
Method 2: Using string.join()
You can also use the string.join() method. First, create a list, append the strings to it, and use the string join() method to merge them to get the final string.
first_name = "Millie"
last_name = "Brown"
# printing first_name string
print("The first name: " + str(first_name))
# printing last_name string
print("The middle name : " + str(last_name))
# Create a list of Strings
listOfStrings = [first_name, last_name]
final_name = "".join(listOfStrings)
# print the final result
print("The appended string is: " + final_name)
Output
The first name: Millie
The middle name : Brown
The appended string is: MillieBrown
Method 3: Using f-strings
As of the 3.6 version, Python f-strings is a comprehensive new way to format strings. Not only are they more readable, but they are also more concise and less prone to error than other ways of formatting, and also they are faster! You can also concate the strings using f-strings.
first_name = "Millie"
last_name = "Brown"
# printing first_name string
print("The first name: " + str(first_name))
# printing last_name string
print("The middle name : " + str(last_name))
# use f-strings to concat the strings.
final_name = f"{first_name}{last_name}"
# print result
print("The appended string is: " + final_name)
Output
The first name: Millie
The middle name : Brown
The appended string is: MillieBrown
Method 4: Using string.format()
The string.format() method takes the value parameter in the syntax above and inserts it into the curly bracket. The resulting value will be a string.
first_name = "Millie"
last_name = "Brown"
# printing first_name string
print("The first name: " + str(first_name))
# printing last_name string
print("The middle name : " + str(last_name))
print("The appended string is: {}{}".format(first_name, last_name))
Output
The first name: Millie
The middle name : Brown
The appended string is: MillieBrown
That’s it.