Search code examples
pythonsubstitutionlowercasepython-re

Make strings lowercase only after an right arrow


I'd like to make strings lowercase only after an right arrow (and until it hits a comma) in Python.
Also, I prefer to write it in one-line, if I could.
Here's my code:

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?

I believe that there must be a better way. How would you guys do?
Thank you in advance.


Solution

  • 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.
    

    From the documentation:

    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.