使用乘法运算符在Python中创建字符串的多个副本
在本文中,我们将看到如何使用乘法运算符(*) 创建字符串的多个副本。 Python支持对字符串执行某些操作,乘法运算符就是其中之一。
方法一:
只需在要复制的字符串上使用乘法运算符,即可复制所需的次数。
语法:
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
示例 1:
Python3
# 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}")
Python3
# 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}")
Python3
# 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}")
Python3
# initializing a string with all True's
a = [True]*5
print(a)
# Initializing a list with all 0
a = [0]*10
print(a)
输出:
Orignal string is: Geeks
New string is: GeeksGeeksGeeks
示例 2:
蟒蛇3
# 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}")
Original string is: Hello
New string is: HelloHelloHelloHelloHello
输出:
Orignal string is: Hello
New string is: HelloHelloHelloHelloHello
方法 2:多次复制列表中给定的字符串
如果我们有一个字符串作为列表元素,并且我们在列表上使用乘法运算符,我们将得到一个新列表,其中包含复制指定次数的相同元素。
句法:
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.
示例 3 :
蟒蛇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}")
输出:
Original list is: [‘Geeks’]
List after multiplication is: [‘Geeks’, ‘Geeks’, ‘Geeks’]
示例 4 :相同方法的速记方法
蟒蛇3
# initializing a string with all True's
a = [True]*5
print(a)
# Initializing a list with all 0
a = [0]*10
print(a)
输出:
[True, True, True, True, True]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]