Skip to content

Instantly share code, notes, and snippets.

@kshirsagarsiddharth
Created July 20, 2020 07:44
Show Gist options
  • Select an option

  • Save kshirsagarsiddharth/c040d216d5ce870855004398fecd5aa0 to your computer and use it in GitHub Desktop.

Select an option

Save kshirsagarsiddharth/c040d216d5ce870855004398fecd5aa0 to your computer and use it in GitHub Desktop.
replacing with keeping cases constant
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