Python has multiple ways to write string literals. We can convert any of these string types to raw as well. You can write a string with single quotes or double quotes.
Python raw string
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”.
str = "Well\thello beautiful\nsaid by joker" print(str)
Well hello beautiful said by joker
Here, 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.
raw_str = r"Well\thello beautiful\nsaid by joker" print(raw_str)
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
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)
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)
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)
invalidRawA = r"\" ^ SyntaxError: EOL while scanning string literal
OR these kinds of raw strings are invalid.
invalidRawB = r"abc\" invalidRawC = r"abc\\\"
Python raw strings operate backslash (\ ) as a literal character. For example, if we want to print a string with a “\t” inside, it will add space. But if we make it a raw string, it will only print out the “\t” as a regular character.
In this example, we have seen how to create a raw string, when to use it, and what an invalid raw string is. That is it for this tutorial.