【发布时间】:2018-03-31 15:45:59
【问题描述】:
我遇到了一个问题陈述,我必须将句子中的第一个字符和后面单词的后续字符大写。我想出了一个使用正则表达式的解决方案,但我不得不使用两个正则表达式来完成工作。
有没有办法将这两个正则表达式组合成一个?
import re
def capitalize(string):
l2 = re.findall(r'([^\d][a-zA-Z]+\w*)', string) # reg exp1
l4 = re.findall(r'(^[a-zA-Z]+\w*)', string) # reg exp2
# Is there a way of combining these?
if l4 not in l2:
l2.extend(l4)
l3 = {e: e.title() for e in l2}
newstring = string
for item in l3:
newstring = newstring.replace(item, l3[item])
return newstring
validatorvalue = 'q w e r G H J K M' # => o/p 'Q W E R G H J K M'
# validatorvalue = 'hello world lol' => o/p 'Hello World Lol'
# validatorvalue = "1 w 2 r 3g" => "1 W 2 R 3g"
print(capitalize(validatorvalue))
我必须坚持使用这两个正则表达式,因为这是上述 2 个测试用例通过标准的唯一方法。
【问题讨论】:
-
这些模式对我来说毫无意义。也永远不要以小写 l 开始变量
-
或者,在上面的示例中,如果您只想匹配前面有空格或字符串开头的小写 ASCII 字母,请使用
(?<!\S)[a-z]。
标签: python regex string python-3.x