不接受Python Literal r'\' [英] Python Literal r'\' Not Accepted
问题描述
r'\'
不能按预期工作.而不是返回其中包含一个字符(反斜杠)的字符串,而是引发SyntaxError. r"\"
也是一样.
r'\'
in Python does not work as expected. Instead of returning a string with one character (a backslash) in it, it raises a SyntaxError. r"\"
does the same.
如果您具有如下所示的Windows路径列表,那么这将很麻烦:
This is rather cumbersome if you have a list of Windows paths like these:
paths = [ r'\bla\foo\bar',
r'\bla\foo\bloh',
r'\buff',
r'\',
# ...
]
为什么没有接受此文字的充分理由?
Is there a good reason why this literal is not accepted?
推荐答案
我的问题的答案(为什么不允许在原始字符串中将反斜杠用作最后一个字符?")实际上对我来说似乎是这是一个设计决策" ,还有一个值得怀疑的地方.
The answer to my question ("Why is a backslash not allowed as last character in raw strings?") actually to me seems to be "That's a design decision", furthermore a questionable one.
一些答案试图说明词法分析器和某些语法突出显示器以这种方式更简单.我不同意(并且我在编写解析器和编译器以及IDE开发方面有一定的背景知识).使用反斜杠没有任何特殊含义的语义来定义原始字符串会更简单. lexer和IDE都将从这种简化中受益.
Some answers tried to reason that the lexer and some syntax highlighters are simpler this way. I don't agree (and I have some background on writing parsers and compiler as well as IDE development). It would be simpler to define raw strings with the semantics that a backslash has no special meaning whatsoever. Both lexer and IDE would benefit from this simplification.
目前的情况也是疣:如果我想要引用在原始字符串中,无论如何我都不能使用它.如果我恰好想要在原始字符串中加一个反斜杠后跟一个引号,则只能使用它.
The current situation also is a wart: In case I want a quote in a raw string, I cannot use this anyway. I only can use it if I happen to want a backslash followed by a quote inside my raw string.
我建议对此进行更改,但是我也看到了破坏现有代码的问题:-/
I would propose to change this, but I also see the problem of breaking existing code :-/
这篇关于不接受Python Literal r'\'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!