python - 为什么我不能用反斜杠结束原始字符串?

标签 python string rawstring

<分区>

我在这里很困惑,即使原始字符串将每个 \ 转换为 \\ 但是当这个 \ 最后出现时它会引发错误.

>>> r'so\m\e \te\xt'
'so\\m\\e \\te\\xt'

>>> r'so\m\e \te\xt\'
SyntaxError: EOL while scanning string literal

更新:

这现在包含在 Python FAQs 中还有:Why can’t raw strings (r-strings) end with a backslash?

最佳答案

你仍然需要 \ 来转义原始字符串中的 '",否则 python 解释器不知道字符串在哪里停止. 在您的示例中,您正在转义结束 '

否则:

r'it wouldn\'t be possible to store this string'
r'since it'd produce a syntax error without the escape'

查看语法突出显示以了解我的意思。

关于python - 为什么我不能用反斜杠结束原始字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11168076/

相关文章:

c++ - clang-format (12.0.1) 的什么设置不会在 C++ 中的 R 前缀和原始字符串之间添加空格?

c++ - 如何从 Vim 中的语法突出显示中排除 C++ 原始字符串文字?

python - 在 Python 中自动键入转换参数

python - 如何确定描述符的类别?

python - MacOS Big Sur - Python ctypes find_library 找不到库(ssl、CoreFoundation 等)

python - 从包含数百万个文件的目录 (bash/python/perl) 中通过精确匹配有效地查找数千个文件

c - c程序中的总线错误10

c# - 将原始字符串转换为 MimeMessage

php mysql 最大值忽略字母

java - 如何用空格分隔单词?