This python tutorial help to learn different ways to append a string in python. There are various ways, such as using the += operator, join() function, f-strings, and appending the strings with space.
As we know, The strings in Python are immutable objects. You can not modify the original string, but you can always return a new string. Let’s discuss the concatenation of strings and how to append one string to another string.
You can append a string using the below ways:
- Using + Operator
- Using string.join() method
- Using Python f-strings
Python append String
Python uses the +=
operator to attach one string to another. A string is appended to another with the Python += operator. The final value is then assigned to a variable after adding the two initial values.
Python append string Using + Operator
We can concatenate strings by using +=
(plus equal operator) to concatenate two strings, a new string is created without a change of the original string.
#app.py fname = "Tim" mname = "Tom" # printing fname string print("The first name: " + str(fname)) # printing mname add string print("The middle name : " + str(mname)) # Using += operator adding one string to another fname += mname # print result print("The concatenated string is: " + fname)
Output:
The first name: Tim The middle name : Tom The concatenated string is: TimTom
How To Append string multiple times in Python
You can append strings multiple times using + operator
. Let’s create a user-defined function that will append the string n times to the original string.
# app.py str = 'Tim' def string_append(s, n): op = '' i = 0 while i < 5: op += s + ',' i = i + 1 return op jstring = string_append(str, 5) print(jstring)
Output:
Tim-Tim-Tim-Tim-Tim
String join() method to append a string
Python’s string join()
method can be used to append strings. You must make a list and add the strings to it to accomplish that. To combine them and produce the final string, use the string join()
function.
#app.py fname = "Tim" mname = "Tom" # printing fname string print("The first name: " + str(fname)) # printing mname add string print("The middle name : " + str(mname)) listOfStrings = [fname, mname] finalString = "".join(listOfStrings) # print result print("The concatenated string is: " + fname)
The first name: Tim The middle name : Tom The concatenated string is: TimTom
Python append String Using f-strings
Python f-strings
, is a new method for formatting strings, It’s available as of version python 3.6. In comparison to other formatting methods, they are not only faster but also more readable.
#app.py fname = "Tim" mname = "Tom" # printing fname string print("The first name: " + str(fname)) # printing mname add string print("The middle name : " + str(mname)) finalString = f"{fname}{mname}" # print result print("The concatenated string is: " + fname)
Output:
The first name: Tim The middle name : Tom The concatenated string is: TimTom