Created
July 20, 2020 07:44
-
-
Save kshirsagarsiddharth/c040d216d5ce870855004398fecd5aa0 to your computer and use it in GitHub Desktop.
replacing with keeping cases constant
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def matchcase(word): | |
| def replace(m): | |
| text = m.group() | |
| if text.isupper(): | |
| return word.upper() | |
| elif text.islower(): | |
| return word.lower() | |
| elif text[0].isupper(): | |
| return word.capitalize() | |
| else: | |
| return word | |
| return replace | |
| text = "HELLO WORLD, hello world, Hello World" | |
| re.sub("hello",matchcase('good morning'),text,flags=re.IGNORECASE) | |
| # Output: 'GOOD MORNING WORLD, good morning world, Good morning World' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment