This article shows you how to use the multiplication operator (*) to make multiple copies of a string. Python supports certain string operations, including the multiplication operator.
Syntax:
str2 = str1 * N where str2 is the new string where you want to store the new string str1 is the original string N is the number of the times you want to copy the string. After using multiplication operator we get a string as output
Example 1:
# Original string a = "Geeks" # Multiply the string and store # it in a new string b = a*3 # Display the strings print(f"Orignal string is: {a}") print(f"New string is: {b}")
Output:
Orignal string is: Geeks New string is: GeeksGeeksGeeks
Output:
Orignal string is: Geeks New string is: GeeksGeeksGeeks
Example 2:
# Initializing the original string a = "Hello" n = 5 # Multiplying the string b = a*n # Print the strings print(f"Original string is: {a}") print(f"New string is: {b}")
Output
Original string is: Hello New string is: HelloHelloHelloHelloHello
Output:
Orignal string is: Hello New string is: HelloHelloHelloHelloHello
If we have a string as a list element and use the multiplication operator in the list, we get a new list containing the same element copied multiple times.
Syntax:
a = [“str1”] * N a will be a list that contains str1 N number of times. It is not necessary that the element we want to duplicate in a list has to be a string. Multiplication operator in a list can duplicate anything.
Example 3:
# Initialize the list a = ["Geeks"] # Number of copies n = 3 # Multiplying the list elements b = a*n # print the list print(f"Original list is: {a} ") print(f"List after multiplication is: {b}")
Output:
Original list is: [‘Geeks’] List after multiplication is: [‘Geeks’, ‘Geeks’, ‘Geeks’]
Example 4: Shorthand method for the same approach
# initializing a string with all True's a = [True]*5 print(a) # Initializing a list with all 0 a = [0]*10 print(a)
Output:
[True, True, True, True, True] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]