1
0
mirror of https://github.com/satwikkansal/wtfpython synced 2024-11-22 11:04:25 +01:00

Expand strings and backslashes

Resolves https://github.com/satwikkansal/wtfpython/issues/69
This commit is contained in:
Satwik Kansal 2019-06-08 02:53:53 +05:30
parent e0cb30bf3b
commit 092dd096bf

41
README.md vendored
View File

@ -702,30 +702,47 @@ SyntaxError: invalid syntax
---
### ▶ Backslashes at the end of string
### ▶ Strings and the backslashes\
**Output:**
```
>>> print("\\ C:\\")
\ C:\
>>> print(r"\ C:")
\ C:
>>> print(r"\ C:\")
```py
>>> print("\"")
"
>>> print(r"\"")
\"
>>> print(r"\")
File "<stdin>", line 1
print(r"\ C:\")
print(r"\")
^
SyntaxError: EOL while scanning string literal
>>> r'\'' == "\\'"
True
```
#### 💡 Explanation
- In a raw string literal, as indicated by the prefix `r`, the backslash doesn't have the special meaning.
- In a normal python string, the backslash is used to escape characters that may have special meaning (like single-quote, double-quote and the backslash itself).
```py
>>> print(repr(r"wt\"f"))
'wt\\"f'
>>> 'wt\"f'
'wt"f'
```
- What the interpreter actually does, though, is simply change the behavior of backslashes, so they pass themselves and the following character through. That's why backslashes don't work at the end of a raw string.
- In a raw string literal (as indicated by the prefix `r`), the backslashes pass themselves as is along with the behavior of escaping the following character.
```py
>>> r'wt\"f' == 'wt\\"f'
True
>>> print(repr(r'wt\"f')
'wt\\"f'
>>> print("\n")
>>> print(r"\\n")
'\\\\n'
```
- This means when a parser encounters a backslash in a raw string, it expects another character following it. And in our case (`print(r"\")`), the backslash escaped the trailing quote, leaving the parser without a terminating quote (hence the `SyntaxError`). That's why backslashes don't work at the end of a raw string.
---