Last active
September 3, 2018 22:14
-
-
Save nicksspirit/736d1ddb0e4aad689324051c37c139bc to your computer and use it in GitHub Desktop.
replace multiple substrings in a string.
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
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