Geek Logbook

Tech sea log book

 Escape sequences in Pyhon

Escape sequences as in C

While reading Automate the Boring Stuff with Python: Practical Programming for Total Beginners, I noticed the existence of raw strings. A raw string is created in such a way that escape sequences listed in the Python documentation are not processed.

In fact, at the beginning of the section on Lexical Analysis, we can read:

Unless an 'r' or 'R' prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C.

https://docs.python.org/3/reference/lexical_analysis.html#escape-sequences

As an example we are going to receive the following output

Examples from random escape sequences

print(f"this a\n string")
this a 
 string
print(f"this a\" string")
this a" string
print(f"this a\t string")
this a   string

Using Raw String

print(r"this a\n string")
this a\n string
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *.