Python – 在潜在单词之间添加空格
给定字符串列表,任务是在以大写字母开头的序列之前添加一个空格。
Input : test_list = [“gfgBest”, “forGeeks”, “andComputerScienceStudents”]
Output : [‘gfg Best’, ‘for Geeks’, ‘and Computer Science Students’]
Explanation : Words segregated by Capitals.
Input : test_list = [“ComputerScienceStudentsLoveGfg”]
Output : [‘Computer Science Students Love Gfg’]
Explanation : Words segregated by Capitals.
方法 #1:使用循环 + join()
这是可以执行此任务的方式之一。在此,我们执行迭代所有字符串的任务,然后迭代所有字符,然后以暴力方式使用循环添加空格。 isupper() 用于检查大写字符。
Python3
# Python3 code to demonstrate working of
# Add Space between Potential Words
# Using loop + join()
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
res = []
# loop to iterate all strings
for ele in test_list:
temp = [[]]
for char in ele:
# checking for upper case character
if char.isupper():
temp.append([])
# appending character at latest list
temp[-1].append(char)
# joining lists after adding space
res.append(' '.join(''.join(ele) for ele in temp))
# printing result
print("The space added list of strings : " + str(res))
Python3
# Python3 code to demonstrate working of
# Add Space between Potential Words
# Using regex() + list comprehension
import re
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
# using regex() to perform task
res = [re.sub(r"(\w)([A-Z])", r"\1 \2", ele) for ele in test_list]
# printing result
print("The space added list of strings : " + str(res))
输出
The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
The space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science']
方法 #2:使用 regex() + 列表理解
上述功能的组合也可以用来解决这个问题。在此我们使用正则表达式代码来检查大写字母并使用列表理解执行空格添加和连接。
Python3
# Python3 code to demonstrate working of
# Add Space between Potential Words
# Using regex() + list comprehension
import re
# initializing list
test_list = ["gfgBest", "forGeeks", "andComputerScience"]
# printing original list
print("The original list : " + str(test_list))
# using regex() to perform task
res = [re.sub(r"(\w)([A-Z])", r"\1 \2", ele) for ele in test_list]
# printing result
print("The space added list of strings : " + str(res))
输出
The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
The space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science']