简体   繁体   中英

string manipulation in python to convert the case of a word that comes next to "caps lock"

I want to write a python code where given a string from user

s = "hello, caps lock people of caps lock stackoverflow !"

and should return "hello, PEOPLE of STACKOVERFLOW !"

Note: PEOPLE Aand STACKOVERFLOW are uppercase.

Cant figure how to do this. please help!

We can try using re.sub with a callback function:

def to_upper(match):
    return match.group(1).upper()

s = "hello, caps lock people of caps lock stackoverflow !"
out = re.sub(r'\bcaps lock (\S+)', to_upper, s)
print(out)

This prints:

hello, PEOPLE of STACKOVERFLOW !

The approach here is to use re.sub to find every occurrence of caps lock followed by some word. Then, this word match is passed to the callback function to_upper() which then returns the uppercase version as the replacement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM