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 committed by Satwik
parent a0832c4459
commit f3b96e4d7f

49
README.md vendored
View File

@ -704,30 +704,47 @@ SyntaxError: invalid syntax
--- ---
### ▶ Backslashes at the end of string ### ▶ Strings and the backslashes\
**Output:** **Output:**
``` ```py
>>> print("\\ C:\\") >>> print("\"")
\ C:\ "
>>> print(r"\ C:")
\ C:
>>> print(r"\ C:\")
File "<stdin>", line 1 >>> print(r"\"")
print(r"\ C:\") \"
^
>>> print(r"\")
File "<stdin>", line 1
print(r"\")
^
SyntaxError: EOL while scanning string literal SyntaxError: EOL while scanning string literal
>>> r'\'' == "\\'"
True
``` ```
#### 💡 Explanation #### 💡 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 ```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.
--- ---