Preventing Escape Sequence Interpretation in Python
There are instances where we don’t want the strings to behave in this way. In those cases, we generally want to preserve the backslashes. Some of the situations in which this may be required are:
- The string contains a Network or Local path
- The string contains regex, which would further be processed by the regex engine
Methods of Preventing Python Escape Sequence
Here are a few methods demonstrating the prevention of Escape Sequences in Python.
Method 1: Using double Backslashe (\\)
Consistently doubling the backslashes, also allows us to overcome such issues. In this method, we manually find every single backslash in the string and concatenate another backslash to it (at its immediate position). Generally, a tedious method, and only advised if the string size is less.
Python3
# sample string s = "I love to use \t instead of using 4 spaces" # normal output print (s) # doubling line backslashes s = "I love to use \\t instead of using 4 spaces" # output after doubling print (s) |
Output:
I love to use instead of using 4 spaces I love to use \t instead of using 4 spaces
Method 2: Using Raw String
r’….’ or R’…..’ construct, commonly referred to as raw strings, is used to preserve the escape sequences as literals. Such that it does what the previous method did but automatically (does not require human intervention). For turning a normal string into a raw string, prefix the string (before the quote) with an r or R. This is the method of choice for overcoming this escape sequence problem.
Python3
s = "C:\Program Files\norton\appx" # normal output print (s) # changing the string into a raw string s = r "C:\Program Files\norton\appx" # Outputting the raw version of the string print (s) |
Output:
C:\Program Files ortonppx C:\Program Files\norton\appx
Method 3: Using repr() function
The repr() function does not interpret the escape sequence in Python. It returns the object in its printable format.
Python3
str = "I \nlove \tw3wiki" print ( repr ( str )) |
Output:
I love w3wiki 'I \nlove \tw3wiki'
Preventing Escape Sequence Interpretation in Python
Python Escape Sequence is a combination of characters (usually prefixed with an escape character), that has a non-literal character interpretation such that, the character’s sequences which are considered as an escape sequence have a meaning other than the literal characters contained therein. Most Programming languages use a backslash \ as an escape character. This character is used as an escape sequence initiator, any character (one or more) following this is interpreted as an escape sequence. If an escape sequence is designated to a Non-Printable Character or a Control Code, then the sequence is called a control character.
Contact Us