Last modified: Apr 11, 2023 By Alexander Williams
Methods to Append to String in a Loop in Python
Using the += Operator
# Example of using the += operator to append to a string
my_string = ""
for i in range(10):
my_string += str(i) # append each character to the string
print(my_string)
Output:
0123456789
Using the join() Method
# Example of using the join() method to append to a string
my_list = []
for i in range(10):
my_list.append(str(i)) # append each character to the list
my_string = "".join(my_list) # convert the list to a string
print(my_string) # Output: "0123456789"
Output:
0123456789
Using a List and str.join() Method
# Example of using a list and join() method to append to a string
my_list = []
for i in range(10):
my_list.append(str(i)) # append each character to the list
my_string = "".join(my_list) # convert the list to a string
print(my_string) # Output: "0123456789"
Output:
0123456789
Using a List and str.format() Method
# Example of using a list and str.format() method to append to a string
my_string = ""
for i in range(10):
my_string += "{}".format(i) # append each character to the string
print(my_string) # Output: "0123456789"
Output:
0123456789
Using f-Strings (Formatted String Literals)
# Example of using f-Strings to append to a string
my_string = ""
for i in range(10):
my_string += f"{i}" # append each character to the string
print(my_string) # Output: "0123456789"
Output:
0123456789