While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Python raw string is created by prefixing a string literal with ‘r’ or ‘R’. Python raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character.
Let’s say we want to create a string Hi\nHello in python. If we try to assign it to a normal string, the \n will be treated as a new line.
s = 'Hi\nHello' print(s)
Let’s see how raw string helps us in treating backslash as a normal character.
raw_s = r'Hi\nHello' print(raw_s)
Hi\nHello Let’s see another example where the character followed by backslash doesn’t have any special meaning.
>>> s = 'Hi\xHello' File "<input>", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \xXX escape
We got the error because python doesn’t know how to decode ‘\x’ as it doesn’t have any special meaning. Let’s see how we can create the same string using raw strings.
>>> s = r'Hi\xHello' >>> print(s) Hi\xHello
If you are on Python console and create a raw-string like below.
>>> r'Hi\xHello' 'Hi\\xHello'
Don’t get confused with the output having two backslashes. It’s just to show it as a normal python string where backslash is being escaped.
When a backslash is followed by a quote in a raw string, it’s escaped. However, the backslash also remains in the result. Because of this feature, we can’t create a raw string of single backslash. Also, a raw string can’t have an odd number of backslashes at the end. Some of the invalid raw strings are:
r'\' # missing end quote because the end quote is being escaped r'ab\\\' # first two backslashes will escape each other, the third one will try to escape the end quote.
Let’s look at some of the valid raw string examples with quotes.
raw_s = r'\'' print(raw_s) raw_s = r'ab\\' print(raw_s) raw_s = R'\\\"' # prefix can be 'R' or 'r' print(raw_s)
\' ab\\ \\\"
That’s all for a quick introduction of python raw string.
You can checkout complete python script and more Python examples from our GitHub Repository.
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.Sign up
Click below to sign up and get $100 of credit to try our products over 60 days!