Is there a function to remove escape characters from a string ?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Dec 25 08:56:21 EST 2008


On Thu, 25 Dec 2008 11:00:18 +0100, Stef Mientki wrote:

> hello,
> 
> Is there a function to remove escape characters from a string ?
> (preferable all escape characters except "\n").


Can you explain what you mean? I can think of at least four alternatives:

(1) Remove literal escape sequences (backslash-char):
"abc\\t\\ad" => "abcd"
r"abc\t\ad" => "abcd"


(2) Replace literal escape sequences with the character they represent:
"abc\\t\\ad" => "abc\t\ad"


(3) Remove characters generated by escape sequences:
"abc\t\ad" => "abcd"
"abc" => "abc" but "a\x62c" => "ac"

This is likely to be impossible without deep magic.


(4) Remove so-called binary characters which are typically inserted using 
escape sequences:
"abc\t\ad" => "abcd"
"abc" => "abc" but "a\x62c" => "abc"

This is probably the easiest, assuming you have bytes instead of unicode.

import string
table = string.maketrans('', '')
delchars =''.join(chr(n) for n in range(32))

s = string.translate(s, table, delchars)



-- 
Steven



More information about the Python-list mailing list