【问题标题】:Make strings lowercase only after an right arrow仅在右箭头后使字符串小写
【发布时间】:2020-09-14 07:17:17
【问题描述】:

我想只在 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】:
    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.
    

    来自documentation

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

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

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

    【讨论】:

    • 哇,lambda 就像一个魅力!我以前应该知道这一点,因为我为此编写了不必要的冗长代码。非常感谢!
    猜你喜欢
    • 2021-12-06
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多