Escape sequencing in Python

A string already comes with the single (') and double ('') quotes incorporated within its syntax. Hence, if we need to print a single or a double quote within a string, it causes a SyntaxError. To avoid such an error, the quotes—whether they are single or double quotes—must be escaped. This phenomenon is called an escape sequence. An escape sequence begins with a backslash () and can be understood differently. If we intend to use a single quote or a double quote as a string, then it must be escaped by appending a backslash before it. Let's see it in action.

We will show the following example for all three cases (a single quote, a double quote, and a triple quote):

String = '''I'm a "Data Scientist"'''

# Initial String
print("Initial String with use of Triple Quotes: ")
print(String)

# Escaping Single Quote
String = 'I'm a "Data Scientist"'
print(" Escaping Single Quote: ")
print(String)

# Escaping Double Quotes
String = "I'm a "Data Scientist""
print(" Escaping Double Quotes: ")
print(String)

In computer science, we often need to provide a path to some files or datasets on different occasions. This is the same when working with data science. The first step is to load the dataset. To do so, we have to provide a link or path to the file by using a double slash, in order to escape the double slash. We then print the paths with escape sequences, as shown in the following example: 

String = "C:\Python\DataScience\"
print(" Escaping Backslashes: ")
print(String)

The preceding code generates the following output:

Escaping Backslashes: 
C:PythonDataScience

Note the use of the double slash in the code—this provides a single slash as the output. This is why escaping is a very useful mechanism. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.41.229