仅在右箭头后将字符串设为小写
Make strings lowercase only after an right arrow
我只想在 Python.
中的右箭头之后(直到它碰到逗号)将字符串设为小写
另外,如果可以的话,我更喜欢用一行写。
这是我的代码:
import re
line = "For example, →settle ACCOUNTs. After that, UPPER CASEs are OK."
string1 = re.sub(r'→([A-Za-z ]+)', r'→', line)
# string1 = re.sub(r'→([A-Za-z ]+)', r'→.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?
我相信一定有更好的方法。你们会怎么做?
提前谢谢你。
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
can be a string or a function...
If repl
is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
我只想在 Python.
中的右箭头之后(直到它碰到逗号)将字符串设为小写
另外,如果可以的话,我更喜欢用一行写。
这是我的代码:
import re
line = "For example, →settle ACCOUNTs. After that, UPPER CASEs are OK."
string1 = re.sub(r'→([A-Za-z ]+)', r'→', line)
# string1 = re.sub(r'→([A-Za-z ]+)', r'→.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?
我相信一定有更好的方法。你们会怎么做?
提前谢谢你。
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
can be a string or a function...If
repl
is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.