Table of Contents
💡 Quick Definition
Prefix r before String denotes raw Strings in Python. Python raw string considers backslash (\) as a literal character. This is generally preferred when you don’t want to treat backslash character as escape character.
Here is an example:
1234 s = r"\n \t are escape characters in Python"print(s)
Output:
\n \t are escape characters in Python
Escape sequences provide an efficient way to convey some alternative meaning of a character to the compiler. Some common escape sequences include \n
for new line, \t
for horizontal tabs, and more.
Python also supports such escape sequences and the Python interpreter uses their defined meanings when it encounters such sequences.
For example,
1 2 3 4 |
s = "java \n2 blog" print(s) |
Output:
2 blog
In the above example, we use the \n
sequence to specify that a new line needs to be added.
Prefix r
Before String in Python
Now there might be situations where we are required to display backslashes in the string and not want them to be understood as an escape sequence.
For such situations, we use the prefix r
before String in Python. This r
prefix tells the interpreter that the given string is a raw string literal. Every character in such a string is taken as a string character and backslashes are not interpreted as escape sequences.**
See the code below.
1 2 3 4 |
s = r"java \n2 blog" print(s) |
Output:
In the above example, we use the same string we did in the earlier used code but use the prefix r
before string in Python. It tells the compiler that it is a raw string literal and thus the \n
escape sequence is interpreted as a string and no new line gets added to the string.
Further reading:
Now, there is a distinction in using the r
prefix in Python 2 and Python 3. The former considers strings as ASCII-encoded letters whereas the latter expands on the character set and considers strings as a collection of Unicode characters.
In Python 2, we use the prefix u
if we wish to use Unicode characters in a string. We can use this along with the r
prefix by combining them as ur
. If we use the ur
prefix before a string then we are specifying to the compiler that we are creating raw string literals with Unicode characters.
For example,
1 2 3 4 |
a = ur'java\n2blog' print a |
Output:
Conclusion
To conclude this tutorial, we discussed the prefix r
before string in Python. First, we discussed the significance of escape sequences. Then, we went on to demonstrate the use of raw string literals that can be created using the prefix r
before string in Python. We also demonstrated the use of the ur
prefix in Python 2 to create string literals with Unicode characters.