gpt4 book ai didi

Python 文字 r'\' 不被接受

转载 作者:IT老高 更新时间:2023-10-28 20:51:17 25 4
gpt4 key购买 nike

Python 中的

r'\' 无法按预期工作。它不是返回一个包含一个字符(反斜杠)的字符串,而是引发一个 SyntaxError。 r"\" 也一样。

如果你有这样的 Windows 路径列表,这会相当麻烦:

paths = [ r'\bla\foo\bar',
r'\bla\foo\bloh',
r'\buff',
r'\',
# ...
]

这个文字不被接受有充分的理由吗?

最佳答案

这是根据 documentation :

When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal r"\n" consists of two characters: a backslash and a lowercase 'n'. String quotes can be escaped with a backslash, but the backslash remains in the string; 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 string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.

使用 "\\" 代替,或者,甚至更好的是,使用 / 作为路径分隔符(是的,这适用于 Windows)。

关于Python 文字 r'\' 不被接受,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9993390/

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