2222HEX_ENCODED_CHAR_REGEX = r"(?P<result>\\x[0-9A-Fa-f]{2})"
2323
2424# Raw chars that will be safe encoded to their slash (\) representations (e.g. newline to \n)
25- SAFE_ENCODE_SLASH_REPLACEMENTS = "\\ \t \n \r \x0b \x0c "
25+ SAFE_ENCODE_SLASH_REPLACEMENTS = "\t \n \r \x0b \x0c "
26+
27+ # String used for temporary marking of slash characters
28+ SLASH_MARKER = "__SLASH__"
2629
2730def safecharencode (value ):
2831 """
@@ -37,9 +40,14 @@ def safecharencode(value):
3740 retVal = value
3841
3942 if isinstance (value , basestring ):
43+
44+ retVal = retVal .replace ('\\ ' , SLASH_MARKER )
45+
4046 for char in SAFE_ENCODE_SLASH_REPLACEMENTS :
4147 retVal = retVal .replace (char , repr (char ).strip ('\' ' ))
4248
49+ retVal = retVal .replace (SLASH_MARKER , '\\ \\ ' )
50+
4351 retVal = reduce (lambda x , y : x + (y if (y in string .printable or ord (y ) > 255 ) else '\\ x%02x' % ord (y )), retVal , unicode ())
4452
4553 elif isinstance (value , list ):
@@ -64,9 +72,13 @@ def safechardecode(value):
6472 else :
6573 break
6674
75+ retVal = retVal .replace ('\\ \\ ' , SLASH_MARKER )
76+
6777 for char in SAFE_ENCODE_SLASH_REPLACEMENTS [::- 1 ]:
6878 retVal = retVal .replace (repr (char ).strip ('\' ' ), char )
6979
80+ retVal = retVal .replace (SLASH_MARKER , '\\ ' )
81+
7082 elif isinstance (value , (list , tuple )):
7183 for i in xrange (len (value )):
7284 retVal [i ] = safechardecode (value [i ])
0 commit comments