Python - 字符串列表中的自定义空间大小填充
在本文给出的字符串列表中,任务是编写一个Python程序,用指定的所需前导和尾随空格数填充每个字符串。
例子:
Input: test_list = [“Gfg”, “is”, “Best”], lead_size = 3, trail_size = 2
Output: [‘ Gfg ‘, ‘ is ‘, ‘ Best ‘]
Explanation: Each word starts after 3 spaces and add 2 spaces after completion.
Input: test_list = [“Gfg”, “Best”], lead_size = 3, trail_size = 2
Output: [‘ Gfg ‘, ‘ Best ‘]
Explanation: Each word starts after 3 spaces and add 2 spaces after completion.
方法#1:使用循环
在此,我们使用循环执行添加尾随和前导所需空格的任务。 *运算符用于获取所需的空格数。
Python3
# Python3 code to demonstrate working of
# Custom space size padding in Strings List
# Using loop
# initializing lists
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list is : " + str(test_list))
# initializing padding numbers
lead_size = 3
trail_size = 2
res = []
for ele in test_list:
# * operator handles number of spaces
res.append((lead_size * ' ') + ele + (trail_size * ' '))
# printing result
print("Padded Strings : " + str(res))
Python3
# Python3 code to demonstrate working of
# Custom space size padding in Strings List
# Using list comprehension
# initializing lists
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list is : " + str(test_list))
# initializing padding numbers
lead_size = 3
trail_size = 2
# using list comprehension for one liner alternative
res = [(lead_size * ' ') + ele + (trail_size * ' ') for ele in test_list]
# printing result
print("Padded Strings : " + str(res))
输出:
The original list is : ['Gfg', 'is', 'Best']
Padded Strings : [' Gfg ', ' is ', ' Best ']
方法#2:使用列表理解
与上述类似,唯一的区别是使用列表理解作为解决问题的单线替代方法。
蟒蛇3
# Python3 code to demonstrate working of
# Custom space size padding in Strings List
# Using list comprehension
# initializing lists
test_list = ["Gfg", "is", "Best"]
# printing original list
print("The original list is : " + str(test_list))
# initializing padding numbers
lead_size = 3
trail_size = 2
# using list comprehension for one liner alternative
res = [(lead_size * ' ') + ele + (trail_size * ' ') for ele in test_list]
# printing result
print("Padded Strings : " + str(res))
输出:
The original list is : ['Gfg', 'is', 'Best']
Padded Strings : [' Gfg ', ' is ', ' Best ']