我需要帮助来找到在字符串python 中合并连续大写字符的最佳python方法
Example:
Input: You can pay N O W or Pay me Back MY Money later
Output: You can pay NOW or Pay me Back MY Money later
我要用一个非常快的&脏进近临时
s='lets P A Y N O W'
new_s = s
replace_maps = []
replace_str = ''
prev_cap = False
for i, c in enumerate(s):
if c == ' ':
continue
if c.isupper():
if prev_cap:
replace_str += c
else:
start = i
replace_str = c
prev_cap = True
else:
end = i
if prev_cap:
replace_maps.append([start, end, replace_str])
prev_cap = False
replace_str = ''
else:
end = i
if prev_cap:
replace_maps.append([start, end, replace_str])
prev_cap = False
replace_str = ''
new_s = s[:replace_maps[0][0]] + replace_maps[0][2] + s[replace_maps[0][1]:]
new_s
Output: lets PAYNOWW
最好使用Look ahead?=
和Look behinds?<=
并检查大写字母。
有关regex 的更多信息
该正则表达式应使作业成为
import re
data = "I could not find a C O V I D patient in the hospital."
re.sub(r"(?<=[A-Z])s(?=[A-Z])", r'', data)
'I could not find a COVID patient in the hospital.'
编辑
关于问题修改后的新输入
data = "You can pay N O W or Pay me Back MY Money later"
re.sub(r"(?<=[A-Z])s(?=[A-Z] )", r'', data)
输出
'You can pay NOW or Pay me Back MY Money later'
不带正则表达式:
mystring = mystring.split(" ")
res = mystring[0]
for i in range(1, len(mystring)):
if not (mystring[i-1].isupper() and mystring[i].isupper()):
res+= " "
res += mystring[i]
我不知道最蟒蛇的方式是什么。我只能告诉你我想到了什么。
import re
def merge_cons_up(string):
pattern = re.compile(" [A-Z](?![a-zA-Z0-9_.-])")
sub_text = re.findall(pattern=pattern, string=string)
repl = "".join(sub_text).replace(" ", "")
sub = re.sub(pattern=pattern, string=string, repl=" " + repl, count=1)
final_string = re.sub(pattern=pattern, string=sub, repl="")
return final_string
print(merge_cons_up("I could not find a C O V I D patient in the hospital."))
输出:
I could not find a COVID patient in the hospital.