Python – 字符串中所有可能的空间连接
有时,在使用Python字符串时,我们可能会遇到一个问题,即我们需要在每个可能的单词结尾处构造带有单个空格的字符串。这种应用程序可以发生在我们需要执行测试的域中。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + join()
这是可以执行此任务的蛮力方式。在此,我们使用 join() 执行形成所有可能连接的任务,并使用循环遍历所有字符串的任务。
# Python3 code to demonstrate working of
# All possible space joins in String
# Using loop + join()
# initializing string
test_str = 'Geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# All possible space joins in String
# Using loop + join()
res = []
temp = test_str.split(' ')
strt_idx = 0
lst_idx = len(temp)
for idx in range(len(temp)-1):
frst_wrd = "".join(temp[strt_idx : idx + 1])
scnd_wrd = "".join(temp[idx + 1 : lst_idx])
res.append(frst_wrd + " " + scnd_wrd)
# printing result
print("All possible spaces List : " + str(res))
The original string is : Geeksforgeeks is best for geeks
All possible spaces List : [‘Geeksforgeeks isbestforgeeks’, ‘Geeksforgeeksis bestforgeeks’, ‘Geeksforgeeksisbest forgeeks’, ‘Geeksforgeeksisbestfor geeks’]
方法 #2:使用enumerate() + join() + combinations()
上述方法的组合可用于执行此任务。在此,我们使用组合()执行提取组合的任务。这将打印所有出现的空格的所有组合,而不是上述方法中的一个。
# Python3 code to demonstrate working of
# All possible space joins in String
# Using enumerate() + join() + combinations()
import itertools
# initializing string
test_str = 'Geeksforgeeks is best for geeks'
# printing original string
print("The original string is : " + str(test_str))
# All possible space joins in String
# Using enumerate() + join() + combinations()
res = []
temp = test_str.split(' ')
N = range(len(temp) - 1)
for idx in N:
for sub in itertools.combinations(N, idx + 1):
temp1 = [val + " " if i in sub else val for i, val in enumerate(temp)]
temp2 = "".join(temp1)
res.append(temp2)
# printing result
print("All possible spaces List : " + str(res))
The original string is : Geeksforgeeks is best for geeks
All possible spaces List : [‘Geeksforgeeks isbestforgeeks’, ‘Geeksforgeeksis bestforgeeks’, ‘Geeksforgeeksisbest forgeeks’, ‘Geeksforgeeksisbestfor geeks’, ‘Geeksforgeeks is bestforgeeks’, ‘Geeksforgeeks isbest forgeeks’, ‘Geeksforgeeks isbestfor geeks’, ‘Geeksforgeeksis best forgeeks’, ‘Geeksforgeeksis bestfor geeks’, ‘Geeksforgeeksisbest for geeks’, ‘Geeksforgeeks is best forgeeks’, ‘Geeksforgeeks is bestfor geeks’, ‘Geeksforgeeks isbest for geeks’, ‘Geeksforgeeksis best for geeks’, ‘Geeksforgeeks is best for geeks’]