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 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)
Output:
Hi
Hello
Let’s see how raw string helps us in treating backslash as a normal character.
raw_s = r'Hi\nHello'
print(raw_s)
Output: 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
>>> 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.
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'\''
print(raw_s)
raw_s = r'ab\\'
print(raw_s)
raw_s = R'\\\"' # prefix can be 'R' or 'r'
print(raw_s)
Output:
\'
ab\\
\\\"
That’s all for a quick introduction of python raw string.
Hi expert,
I have a problem about Python Raw String.
I had a list data, it included a string which likes “\183456\data\image”
I want to use this string(a directory) to access a file, but it comes up an error.
“\1” can’t not be regarded as a string, I can’t use the “r” because the list data are dynamically generated.
I would really appreciate if you could answer my question.
Use proper quotation marks!
use re.escape(“\183456\data\image”)
Thanks mate! Quite short and simple, but very handy!
1.
raw_s = r’\”
print(raw_s)
2.raw_s = r’ab\\’
print(raw_s)
how (2) can be correct in raw string,,because as far as i understood rawstring places a backslash whenever it sees a backslash or when it is not escaping a quote.
If that is the case then then it should matter how many consecutive backslashes are present in a string, but it is not dealing in that way ,why?
please make my concept clear.
on console:
1. r’ab\\’ ->>ab\\\\
2. r’ab\\\’
as in first case why not in the second case..