0
Backslash in the end of a raw string in Python 3
Hello everyone! Currently I'm studying regular expressions in Python 3 and in the lesson the term "raw strings" appeared. I googled for it and read that these raw strings mustn't end with backslash, however this worked fine in the SoloLearn sandbox. Was that mentioned implying previous versions of Python?
5 Answers
+ 2
If you end a string with a backslash, the interpreter will recognise your last qoutation mark as part of the string and not the closing mark.
Try this and this will cause an error :
print("This is a string\")
But this will not cause an error:
print("This is a string\" ")
+ 1
ă Nicko12 ă and could u pls tell me why the quotation marks do work when we have two backslashes in the end?
https://code.sololearn.com/ci9dpt4fXq6m/?ref=app
+ 1
Shiki
As we know, backslash ( \ ) is used to escape characters after it. It is the same with ifself, if you place a backslash before a backslash, it means that you escape the backslash that is after the backslash or itself..
print(" Hello \\ World" )
>> Hello \ World
When printing backslash, we want to escape backslash by another backslash as it is used to escape itself.
+ 1
But I see here in your code that you used "r" before the string which means "raw"
For example:
print(r"hello \n world")
This will not print a new line but instead, it will print the \n literally because we used the string prefix "r"
So the output will look like this:
>> hello \n world
Remember that when we use "r" before the string, we cannot use escape sequence as the backslash is now part of the string when using raw strings.
0
Thank you for explaining about the double-backslash under normal conditions.
But I still can't get why exactly in the raw lines I can't use single backslash in the end. I receive the EOL mistake. But if I put two backslashes in the end then it's okay and they are depicted.
print(r"\n\n\") ----> Syntax error: EOL while scanning the string literal
print(r"\n\n\\") ----> n\n\\
Sorry for probably bothering you with the little things and thank you in advance.