为什么我不能用反斜杠结束原始字符串? [英] Why can't I end a raw string with a backslash?
本文介绍了为什么我不能用反斜杠结束原始字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里很困惑,即使原始字符串将每个 \
转换为 \\
但是当这个 \
最后出现时它会引发错误.
更新:
现在 Python 常见问题解答 中也介绍了这一点:为什么可以't 原始字符串(r-strings)以反斜杠结尾?
解决方案
你仍然需要 \
在原始字符串中转义 '
或 "
, 因为否则 python 解释器不知道字符串在哪里停止.在你的例子中,你正在逃避结束的 '
.
否则:
r'不可能存储这个字符串'r'因为它会在没有转义的情况下产生语法错误'
查看语法高亮显示我的意思.
I am confused here, even though raw strings convert every \
to \\
but when this \
appears in the end it raises error.
>>> r'so\m\e \te\xt'
'so\\m\\e \\te\\xt'
>>> r'so\m\e \te\xt\'
SyntaxError: EOL while scanning string literal
Update:
This is now covered in Python FAQs as well: Why can’t raw strings (r-strings) end with a backslash?
解决方案
You still need \
to escape '
or "
in raw strings, since otherwise the python interpreter doesn't know where the string stops. In your example, you're escaping the closing '
.
Otherwise:
r'it wouldn\'t be possible to store this string'
r'since it'd produce a syntax error without the escape'
Look at the syntax highlighting to see what I mean.
这篇关于为什么我不能用反斜杠结束原始字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文