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
ch = "I\nLove\tGeeksforgeeks"
print ("The string after resolving escape character is : ")
print (ch)
|
Output :
The string after resolving escape character is :
I
Love Geeksforgeeks
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
ch = "I\nLove\tGeeksforgeeks"
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 Geeksforgeeks
The string after using repr() is :
'I\nLove\tGeeksforgeeks'
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
ch = "I\nLove\tGeeksforgeeks"
print ("The string without r / R is : ")
print (ch)
print ("\r")
ch1 = r"I\nLove\tGeeksforgeeks"
print ("The string after using r is : ")
print (ch1)
print ("\r")
ch2 = R"I\nLove\tGeeksforgeeks"
print ("The string after using R is : ")
print (ch2)
|
Output :
The string without r/R is :
I
Love Geeksforgeeks
The string after using r is :
I\nLove\tGeeksforgeeks
The string after using R is :
I\nLove\tGeeksforgeeks
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\tforgeeks"
print(string)
|
Output
I
Love Geeksforgeeks
Time Complexity: O(1)
Space Complexity: O(1)
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
24 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...