What is a Raw String in Python

Python raw string is a regular string prefixed with an r or R. To create a raw string in Python, “prefix a string literal with ‘r’ or ‘R'”. The raw string tackles backslash (\) as a literal character. To understand what a raw string means, see the below string, having the sequence “\n” and “\t”.

Example

str = "Well\thello beautiful\nsaid by joker"

print(str)

Output

Well hello beautiful
said by joker

Str is a regular string, so it treats “\n” and “\t” as escape characters.

Let’s create a raw string from it and see how it will turn out.

Example 2

raw_str = r"Well\thello beautiful\nsaid by joker"

print(raw_str)

Output

Well\thello beautiful\nsaid by joker

In this case, the raw string does not treat “\n” and “\t” as escape characters.

Where raw strings are used in Python?

You can use raw strings where “you do not need the processed version of that string”. For example, if your string contains any invalid escape character like \x or \k, it will throw one SyntaxError.

str = "Well\xhello beautiful"

print(str)

Output

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in 
            position 4-5: truncated \xXX escape

You can see that we got a SyntaxError because Python doesn’t know how to decode ‘\x’ as it doesn’t have any special meaning.

This error can be avoided if we use a raw string.

str = r"Well\xhello beautiful"

print(str)

Output

Well\xhello beautiful

Invalid raw strings in Python

If you think that all the raw strings are valid, then you’re mistaken. There can be invalid raw strings. For example, a raw string containing only a single backslash is invalid.

invalidRawA = r"\"

print(invalidRawC)

Output

SyntaxError: EOL while scanning string literal

OR these kinds of raw strings are invalid.

invalidRawB = r"abc\"
invalidRawC = r"abc\\\"

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.