Python Raw String With Examples

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.

Python Raw String

Let’s say we want to create a string HinHello in python. If we try to assign it to a normal string, the n will be treated as a new line.




Let’s see how raw string helps us in treating backslash as a normal character.

raw_s = r'HinHello'

Output: HinHello

Let’s see another example where the character followed by backslash doesn’t have any special meaning.

>>> s="HixHello"
  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'HixHello'
>>> print(s)

If you are on Python console and create a raw-string like below.

>>> r'HixHello'

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.

Python Raw String and Quotes

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'''
raw_s = r'ab\'
raw_s = R'\"'  # prefix can be 'R' or 'r'



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.

By admin

Leave a Reply

%d bloggers like this: