gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:00 25 4
gpt4 key购买 nike

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

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

关于python - 如何在 Python 字符串中包含转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58197060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com