Last active
December 28, 2015 11:59
-
-
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.
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
# 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