📜  使用乘法运算符在Python中创建字符串的多个副本

📅  最后修改于: 2022-05-13 01:55:47.041000             🧑  作者: Mango

使用乘法运算符在Python中创建字符串的多个副本

在本文中,我们将看到如何使用乘法运算符(*) 创建字符串的多个副本。 Python支持对字符串执行某些操作,乘法运算符就是其中之一。

方法一:

只需在要复制的字符串上使用乘法运算符,即可复制所需的次数。

语法

示例 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)


输出:

示例 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

输出:

方法 2:多次复制列表中给定的字符串

如果我们有一个字符串作为列表元素,并且我们在列表上使用乘法运算符,我们将得到一个新列表,其中包含复制指定次数的相同元素。

句法:

示例 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}")

输出:

示例 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)

输出: