python转义序列
Escape sequences allow you to include special characters in strings. To do this, simply add a backslash (\
) before the character you want to escape.
转义序列允许您在字符串中包括特殊字符。 为此,只需在要转义的字符之前添加反斜杠( \
)。
For example, imagine you initialized a string with single quotes:
例如,假设您使用单引号初始化了一个字符串:
s = 'Hey, whats up?'
print(s)
Output:
输出:
Hey, whats up?
But if you include an apostrophe without escaping it, then you will get an error:
但是,如果您在没有转义的情况下加入了撇号,则会出现错误:
s = 'Hey, what's up?'
print(s)
Output:
输出:
File "main.py", line 1
s = 'Hey, what's up?'
^
SyntaxError: invalid syntax
To fix this, just escape the apostrophe:
要解决此问题,只需跳过撇号:
s = 'Hey, what\'s up?'
print(s)
To add newlines to your string, use \n
:
要在字符串中添加换行符,请使用\n
:
print("Multiline strings\ncan be created\nusing escape sequences.")
Output:
输出:
Multiline strings
can be created
using escape sequences.
An important thing to remember is that, if you want to include a backslash character in a string, you will need to escape that. For example, if you want to print a directory path in Windows, you'll need to escape each backslash in the string:
要记住的重要一点是,如果要在字符串中包含反斜杠字符,则需要对此进行转义。 例如,如果要在Windows中打印目录路径,则需要对字符串中的每个反斜杠进行转义:
print("C:\\Users\\Pat\\Desktop")
Output:
输出:
C:\Users\Pat\Desktop
原始字符串 (Raw strings)
A raw string can be used by prefixing the string with r
or R
, which allows for backslashes to be included without the need to escape them. For example:
可以通过在字符串前面加上r
或R
来使用原始字符串,从而可以包含反斜杠而无需对其进行转义。 例如:
print(r"Backslashes \ don't need to be escaped in raw strings.")
Output:
输出:
Backslashes \ don't need to be escaped in raw strings.
But keep in mind that unescaped backslashes at the end of a raw string will cause and error:
但是请记住,在原始字符串末尾使用未转义的反斜杠会引起错误:
print(r"There's an unescaped backslash at the end of this string\")
Output:
输出:
File "main.py", line 1
print(r"There's an unescaped backslash at the end of this string\")
^
SyntaxError: EOL while scanning string literal
常见的转义序列 (Common escape sequences)
Escape Sequence | Meaning |
---|---|
\ | Backslash (\ ) |
' | Single quote (' ) |
" | Double quote (" ) |
\n | ASCII Linefeed (adds newline) |
\b | ASCII Backspace |
转义序列 | 含义 |
---|---|
\ | 反斜杠( \ ) |
' | 单引号( ' ) |
” | 双引号( " ) |
\ n | ASCII换行符(添加换行符) |
\ b | ASCII退格键 |
A full list of escape sequences can be found here in the Python docs.
转义序列的完整列表,可以发现这里的Python文档。
翻译自: https://www.freecodecamp.org/news/escape-sequences-python/
python转义序列