Skip to content

Instantly share code, notes, and snippets.

@xuhdev

xuhdev/backbackslash.py

Last active Dec 28, 2015
Embed
What would you like to do?
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