Skip to content

Instantly share code, notes, and snippets.

@ranelpadon
Last active February 17, 2018 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranelpadon/c21e1c96befff808abd9ef4ff8a2f773 to your computer and use it in GitHub Desktop.
Save ranelpadon/c21e1c96befff808abd9ef4ff8a2f773 to your computer and use it in GitHub Desktop.
Find the restricted symbols in the text and substitute with multiple replacement values.
import re
# Restricted symbols taken from https://en.wikipedia.org/wiki/Filename
symbols = ('/', '\\', '?', '%', '*', ':', '|', '"', '<', '>',)
symbols_replacements = {symbol: '_' for symbol in symbols}
space_replacement = {' ': '-'} # Dash instead of underscore
replacements = {}
replacements.update(symbols_replacements)
replacements.update(space_replacement)
text = 'Hello World 01/01/1970 a/b\c?d%e*f:g|h<i>j"'
# Solution 1
for pattern, repl in replacements.iteritems():
text = re.sub(re.escape(pattern), repl, text)
# Solution 2
# pattern = re.compile('|'.join(map(re.escape, replacements.keys())))
# text = pattern.sub(lambda match: replacements[match.group(0)], text)
# Output: Hello-World-01_01_1970--a_b_c_d_e_f_g_h_i_j_
print text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment