Ways to print escape characters in Python

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\tw3wiki"
 
print ("The string after resolving escape character is : ")
print (ch)


Output :

The string after resolving escape character is : 
I
Love    w3wiki

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.

Using repr()

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\tw3wiki"
 
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    w3wiki


The string after using repr() is : 
'I\nLove\tw3wiki'

 

Using “r/R”

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\tw3wiki"
 
print ("The string without r / R is : ")
print (ch)
 
print ("\r")
 
# using "r" to prevent resolution
ch1 = r"I\nLove\tw3wiki"
 
print ("The string after using r is : ")
print (ch1)
 
print ("\r")
 
# using "R" to prevent resolution
ch2 = R"I\nLove\tw3wiki"
 
print ("The string after using R is : ")
print (ch2)


Output :

The string without r/R is : 
I
Love    w3wiki


The string after using r is : 
I\nLove\tw3wiki


The string after using R is : 
I\nLove\tw3wiki

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\tBeginner\tforBeginner"
print(string)


Output

I
Love    w3wiki

Time Complexity: O(1)
Space Complexity: O(1)