Last active
August 15, 2019 00:56
-
-
Save chumaumenze/e4322cf32afb46bc00b938f9a3c203eb to your computer and use it in GitHub Desktop.
Find and Replace with Regex
This file contains 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
""" | |
Find and Replace with Regex | |
Requires Python 3.6+ | |
""" | |
import re | |
TEST_STRING = "Hello <name>! Welcome to <place_name>. The date is <date2today>." \ | |
"<place_name> is a great place." | |
def find_replace(string, pattern=r"<(\w+)>", **values): | |
matched_result = re.finditer(pattern, string) | |
for match in matched_result: | |
value = values.get(match) | |
if value is not None: | |
string = re.sub(f"<{match}>", f"<{value}>", string) | |
return string | |
if __name__ == '__main__': | |
new_string = find_replace(TEST_STRING, name="World", place_name="Nigeria", | |
date2today="February 14, 2019") | |
print(new_string) | |
# 'Hello <World>! Welcome to <Nigeria>. The date is <February 14, 2019>. <Nigeria> is a great place.' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment