Skip to content

Instantly share code, notes, and snippets.

@xuhdev
Last active December 28, 2015 11:59
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 xuhdev/7497802 to your computer and use it in GitHub Desktop.
Save xuhdev/7497802 to your computer and use it in GitHub Desktop.
Often when your file needs to go through a few filters, the number of backslashes needed for escaping is just horrible! This small script just solves the problem. Works well on Python 2.6 and later as well as Python 3.
# Often when your file needs to go through a few filters, the number of
# backslashes needed for escaping is just horrible! This small script just
# solves the problem. Works well on Python 2.6 and later as well as Python 3.
# This file is under public domain.
# Copyright (C) 2013 Hong Xu <hong@topbug.net>
from __future__ import print_function
import sys
def escape(content, times, escapechar='\\'):
"""
Escape the @escapechar for @times times. The content is either a string or an iterative of strings.
"""
es = escapechar
for i in range(times):
es = es + es
if type(content) is str:
return content.replace(escapechar, es)
else:
ret = []
for c in content:
ret.append(c.replace(escapechar, es))
return ret
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error: How many times will you escape?", file=sys.stderr)
sys.exit(1)
times = int(sys.argv[1])
if len(sys.argv) >= 3:
escapechar = sys.argv[2]
else:
escapechar = '\\'
content = sys.stdin.readlines()
content = escape(content, times, escapechar)
for line in content:
sys.stdout.write(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment