关于 Python 2.x 的 r'' 和 ur''

wingzero520 2012-11-22 10:18:38
>>> print r'\u'
\u
>>> print ur'\u'
File "<stdin>", line 1
SyntaxError: (unicode error) 'rawunicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX
>>>

这是怎么回事?
我初学 python 时记得书上说前面有 r 的字符串 \ 没有特殊含义,但后来发现我错了,实际上字符串里的最后一个 \ 还是被莫名其妙转义了(r'\' 和 ur'\' 都会出错,只要引号里最后一个字符是反斜杠)……好吧,这也就算了。但是上面那个例子,unicode 和 str 的行为居然不一样,请问这是 BUG 还是什麼……哪位高手能详细说一下 r'' 和 ur'' 到底是干嘛的?是不是还有其他的反斜杠后的字符会被偷偷地转义?我真的越来越搞不懂了……谢谢~
...全文
439 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
wingzero520 2012-11-23
  • 打赏
  • 举报
回复
原来如此,的确很奇怪为什么要这么设计。 总之,再次感谢~
angel_su 2012-11-22
  • 打赏
  • 举报
回复
2.4.1. String literals ... 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. When an 'r' or 'R' prefix is used in conjunction with a 'u' or 'U' prefix, then the \uXXXX and \UXXXXXXXX escape sequences are processed while all other backslashes are left in the string. For example, the string literal ur"\u0062\n" consists of three Unicode characters: ‘LATIN SMALL LETTER B’, ‘REVERSE SOLIDUS’, and ‘LATIN SMALL LETTER N’. Backslashes can be escaped with a preceding backslash; however, both remain in the string. As a result, \uXXXX escape sequences are only recognized when there are an odd number of backslashes. 虽说上述文档里有提到你这两个问题,不过个人觉得是设计不良...

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧