Python – List 中的字符串重复和间距
有时在使用Python时,我们可能会遇到一个问题,即我们需要对 list 中的每个字符串进行重复,并为每个出现的字符串附加一个分隔符。这类问题可能出现在日常编程中。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
可以使用循环以蛮力方式执行此任务。在此,我们迭代列表并执行字符串加法和乘法,同时使用合适的运算符进行迭代。
Python3
# Python3 code to demonstrate working of
# String Repetition and spacing in List
# Using loop
# initializing list
test_list = ['gfg', 'is', 'best']
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = '-'
# initializing K
K = 3
# String Repetition and spacing in List
# Using loop
res = []
for sub in test_list:
res.append((sub + delim) * K)
# printing result
print("List after performing operations : " + str(res))
Python3
# Python3 code to demonstrate working of
# String Repetition and spacing in List
# Using join() + list comprehension
# initializing list
test_list = ['gfg', 'is', 'best']
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = '-'
# initializing K
K = 3
# String Repetition and spacing in List
# Using join() + list comprehension
res = []
for sub in test_list:
res.append(delim.join([sub for _ in range(K)]))
# printing result
print("List after performing operations : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best']
List after performing operations : ['gfg-gfg-gfg-', 'is-is-is-', 'best-best-best-']
方法 #2:使用 join() + 列表推导
上述功能的组合也可用于执行此任务。在此,我们使用 join() 执行附加 delim 的任务,而列表推导执行重复任务。避免尾随分隔符。
Python3
# Python3 code to demonstrate working of
# String Repetition and spacing in List
# Using join() + list comprehension
# initializing list
test_list = ['gfg', 'is', 'best']
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = '-'
# initializing K
K = 3
# String Repetition and spacing in List
# Using join() + list comprehension
res = []
for sub in test_list:
res.append(delim.join([sub for _ in range(K)]))
# printing result
print("List after performing operations : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best']
List after performing operations : ['gfg-gfg-gfg', 'is-is-is', 'best-best-best']