Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Replace lower case to upper, and vice versa, simultaneously via ReGex lib

I open this question although a duplicate of it exists in C# lang. (without the relevant resolution needed).

Im trying to replace all the lower case characters in a given string, with upper case chars, and vice versa. This should be done simultaneously with the least time complexity (because of use in high volume of verbal translations).

The IO:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

input:
str_1 = "Www.GooGle.com"

output:
"wWW.gOOgLE.COM"

The code:

import re                   # import RegEx lib

str_1 = "Www.GooGle.com"    # variable tested

def swapLowerUpper(source):
    # takes source string
    # returns group 0 regex to lower and group 1 regex to upper, by source
    return re.sub(r'([A-Z]+)|([a-z]+)', lambda x: x.group(0).lower(), source)

# check the output
print(swapLowerUpper(str_1)

The Question:

I have a hard time in triggering the second group (which index is 1) and apply the attribute ".upper()" on it. My attempt was to open it as {x: x.group(0).lower(), x: x.group(1).upper()} which failed.

>Solution :

Check whether x.group(1) or x.group(2) was matched, and return the appropriate replacement.

def swapLowerUpper(source):
    return re.sub(r'([A-Z]+)|([a-z]+)', lambda x: x.group(1).lower() if x.group(1) else x.group(2).upper(), source)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading