Print string with escape sequences in Python 3

When I have a string with escape sequence and I print it, it looks like this:

>>> string = "Hello\032world!"  
>>> print(string)

I would like to get the escape sequence replaced by its value, so output will look like this

>>> print(string) 
 Hello world! 

Is this possible to accomplish by function I am not aware of or do I need to replace it char by char with custom made function?

Thank you.


I am sorry for bad description of a problem. \032 represents ASCII value of space character and I want to replace it by its value. I want to replace all these representations of an ASCII chars, not only space char.

1 answer

  • answered 2018-04-14 16:43 Kasrâmvd

    What you want to do is retrieving the numbers after \0 which denotes the zero ascii number:

    In [128]: ord('\0')
    Out[128]: 0

    For a 64-bit system there are 64 possible hexadeciamal ascii equivalent for a character. Because the first character after \0 can hold 8 digit and the second one 8 as well which will create 64 possible ascii character.

    Now what you want is the equivalent ascii of the character in base-10 not 8. for example in your case the ascii equivalent of '\032' is 26. In other words Python will give you the base-8 equivalent of 32:

    In [140]: int('32', 8)
    Out[140]: 26

    One way to reverse this back is to using octal formating:

    In [157]: "{0:o}".format(26)
    Out[157]: '32'

    Now if you are aware of a correct range for your hex characters you can use re.sub with a convertor function like following:

    func = lambda x: chr(int("{0:o}".format(ord(


    In [175]: re.sub(r'[\00-\040]',func, s) # This character range is an example you may want to also use a set of characters (between {}) or one specific character 
    Out[175]: 'Hello world!'