让字符串在右箭头之后才小写。

问题描述 投票:0回答:1

我想在Python中让字符串只有在右箭头后才小写(直到碰到逗号)。另外,如果可以的话,我更希望用单行来写。这是我的代码。

import re

line = "For example, →settle ACCOUNTs. After that, UPPER CASEs are OK."

string1 = re.sub(r'→([A-Za-z ]+)', r'→\1', line)
# string1 = re.sub(r'→([A-Za-z ]+)', r'→\1.lower()', line) # Pseudo-code in my brain
print(string1)
# Expecting: "For example, →settle accounts. After that, UPPERCASEs are OK."

# Should I always write two lines of code, like this:
string2 = re.findall(r'→([A-Za-z ]+)', line)
print('→' + string2[0].lower())
# ... and add "For example, " and ". After that, UPPER CASEs are OK." ... later?

我相信一定有更好的方法。你们会怎么做呢?先谢谢你们了。

python substitution lowercase re
1个回答
4
投票
import re

line = "For example, →settle ACCOUNTs. After that, UPPER CASEs are OK."

string1 = re.sub(r'→[A-Za-z ]+', lambda match: match.group().lower(), line)

print(string1)
# For example, →settle accounts. After that, UPPER CASEs are OK.

文件:

re.sub(pattern, repl, string, count=0, flags=0)

...repl 可以是一个字符串或函数...

如果 repl 是一个函数,它对模式的每一个非重叠出现都会被调用。该函数接收一个单一的匹配对象参数,并返回替换的字符串。

© www.soinside.com 2019 - 2024. All rights reserved.