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?

13th Jan 2021, 2:48 AM
Dimitry Buylin
Dimitry Buylin - avatar
5 Respuestas
+ 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\" ")
13th Jan 2021, 4:04 AM
noteve
noteve - avatar
+ 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
13th Jan 2021, 12:20 PM
Dimitry Buylin
Dimitry Buylin - avatar
+ 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.
13th Jan 2021, 12:26 PM
noteve
noteve - avatar
+ 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.
13th Jan 2021, 12:30 PM
noteve
noteve - avatar
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.
13th Jan 2021, 2:25 PM
Dimitry Buylin
Dimitry Buylin - avatar