Skip to main content
 首页 » 编程设计

python之如何在 Python 字符串中包含转义字符

2025年05月04日32artech

我正在尝试使用以下代码动态构建一个字符串

output = "".join(["network", "\", "account"]) 

转义后的结果应该是network\account

如何在 Python3 中执行此操作而不会遇到此错误

File "<stdin>", line 1 
"".join(["network", "\", "account"]) 
                                ^ 
SyntaxError: invalid syntax 

请您参考如下方法:

原始字符串是另一种方式(有人已经使用转义字符发布了答案)。

在引号前加上 r:

r'network\account 

编辑:

我意识到这实际上不适用于您使用单个反斜杠的示例,

我已经发布了:

output = "".join(["network", r"\", "account"]) 

但是根据 Python 文档。

Even in a raw literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw literal cannot end in a single backslash (since the backslash would escape the following quote character).

https://docs.python.org/3/reference/lexical_analysis.html?highlight=raw%20strings