Skip to content

Instantly share code, notes, and snippets.

@nicksspirit
Last active September 3, 2018 22:14
Show Gist options
  • Save nicksspirit/736d1ddb0e4aad689324051c37c139bc to your computer and use it in GitHub Desktop.
Save nicksspirit/736d1ddb0e4aad689324051c37c139bc to your computer and use it in GitHub Desktop.
replace multiple substrings in a string.
from functools import reduce
# Lets define a helper method to make it easy to use
def replacer(text, replacements):
return reduce(
lambda text, ptuple: text.replace(ptuple[0], ptuple[1]),
replacements, text
)
if __name__ == '__main__':
uncleaned_str = "abc&d&ef#ghi"
cleaned_str = replacer(uncleaned_str, [("&", "\&"), ("#", "\#")])
print(cleaned_str) # "abc\&def\#ghi"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment