Escape characters are characters that are generally used to perform certain tasks and their usage in code directs the compiler to take a suitable action mapped to that character. Example :
'\n' --> Leaves a line '\t' --> Leaves a space
Python3
# Python code to demonstrate escape character # string ch = "I\nLove\tGeeksforLazyroar" print ("The string after resolving escape character is : ") print (ch) |
Output :
The string after resolving escape character is : I Love GeeksforLazyroar
But in certain cases it is desired not to resolve escapes, i.e the entire unresolved string has to be printed. These are achieved by following ways.
This function returns a string in its printable format, i.e doesn’t resolve the escape sequences.
Python3
# Python code to demonstrate printing # escape characters from repr() # initializing target string ch = "I\nLove\tGeeksforLazyroar" print ("The string without repr () is : ") print (ch) print ("\r") print ("The string after using repr () is : ") print ( repr (ch)) |
Output :
The string without repr() is : I Love GeeksforLazyroar The string after using repr() is : 'I\nLove\tGeeksforLazyroar'
Adding “r” or “R” to the target string triggers a repr() to the string internally and stops from the resolution of escape characters.
Python3
# Python code to demonstrate printing # escape characters from "r" or "R" # initializing target string ch = "I\nLove\tGeeksforLazyroar" print ("The string without r / R is : ") print (ch) print ("\r") # using "r" to prevent resolution ch1 = r"I\nLove\tGeeksforLazyroar" print ("The string after using r is : ") print (ch1) print ("\r") # using "R" to prevent resolution ch2 = R"I\nLove\tGeeksforLazyroar" print ("The string after using R is : ") print (ch2) |
Output :
The string without r/R is : I Love GeeksforLazyroar The string after using r is : I\nLove\tGeeksforLazyroar The string after using R is : I\nLove\tGeeksforLazyroar
Using raw string notation:
Approach:
We can also use the raw string notation to print escape characters in Python. We just need to add the letter “r” before the opening quote of the string.
Algorithm:
- Define a raw string variable with the required escape sequence.
- Use the print() function to print the string.
Python3
string = "I\nLove\tGeeks\tforLazyroar" print (string) |
I Love GeeksforLazyroar
Time Complexity: O(1)
Space Complexity: O(1)