Python - Using String Escape Sequences

Introduction

You can embed absolute binary values into the characters of a string.

The following code has a five-character string that embeds two characters with binary zero values:

Demo

s = 'a\0b\0c' 
print( s )
print( len(s) )

Result

Here's a string that is all absolute binary escape codes-a binary 1 and 2 (coded in octal), followed by a binary 3 (coded in hexadecimal):

Demo

s = '\001\002\x03' 
print( s )
print( len(s) )

Result

Python displays non-printable characters in hex, regardless of how they were specified.

You can freely combine absolute value escapes and the more symbolic escape types.

The following string contains the characters "test", a tab and newline, and an absolute zero value character coded in hex:

Demo

S = "s\tp\na\x00m" 
print( S )
print( len(S) )

Result

If Python does not recognize the character after a \ as being a valid escape code, it simply keeps the backslash in the resulting string:

Demo

x = "C:\py\code"           # Keeps \ literally (and displays it as \\) 
print( x )
print( len(x) )

Result

To code literal backslashes explicitly such that they are retained in your strings, double them up (\\ is an escape for one \) or use raw strings.

Related Topic