发布于 4年前

Python如何多次打印字符串或列表

你可以对字符串或列表使用乘号(*)。这好像我们可以将它们任意倍增一样。

n = 3 # number of repetitions
my_string = "abcd"
my_list = [1,2,3]
print(my_string*n)
# abcdabcdabcd
print(my_list*n)
# [1,2,3,1,2,3,1,2,3]

一个有趣的用例是定义一个具有特定值的列表-假设为值0

n = 4
my_list = [0]*n # n denotes the length of the required list
# [0, 0, 0, 0]
©2020 edoou.com   京ICP备16001874号-3