Last modified: Apr 11, 2023 By Alexander Williams
Append Character to String In Python (6 Methods)
Using the += Operator
my_string = "" # Original string
character = "a" # Character to append
my_string += character # Append character using += operator
print(my_string)
Output:
a
Using String Concatenation
my_string = "" # Original string
character = "b" # Character to append
my_string = my_string + character # Concatenate original string and character
print(my_string)
Output:
b
Using a List with the join() Method
my_list = []
character = "c" # Character to append
my_list.append(character) # Append character to the list
my_string = "".join(my_list) # Convert the list to a string using join() method
print(my_string) # Output: "c"
Output:
c
Using Formatted String
my_string = "Hello" # Original string
character = "d" # Character to append
my_string = f"{my_string}{character}" # Append character using formatted string
print(my_string)
Output:
Hello d
Using the str.format() Method
my_string = "World" # Original string
character = "e" # Character to append
my_string = "{}{}".format(my_string, character) # Append character using str.format() method
print(my_string)
Output:
Worlde
Using the join() Method with a List Comprehension
my_string = ""
characters = ['f', 'g', 'h'] # Characters to append
my_string = "".join([character for character in characters]) # Append characters using a list comprehension
print(my_string)
Output:
fgh