use*_*r_s 12 python python-3.x
我在旧版本的python(2.x)中编写了一些python代码,我很难使其工作.我正在使用python 3.4
_eng_word = ur"[a-zA-Z][a-zA-Z0-9'.]*"
Run Code Online (Sandbox Code Playgroud)
(它是标记器的一部分)
Kev*_*imm 19
http://bugs.python.org/issue15096
标题:删除对"ur"字符串前缀的
支持当PEP 414在Python 3中恢复对显式Unicode文字的支持时,"ur"字符串前缀被认为是"r"前缀的同义词.
所以,使用'r'而不是'ur'
Mar*_*ers 12
实际上,Python 3.4仅支持u'...'(支持需要在Python 2和3上运行的代码)r'....',但不支持两者.这是因为ur'..'Python 2中的工作方式的语义与ur'..'Python 3中的工作方式不同(在Python 2中,\uhhhh并且\Uhhhhhhhh仍在处理转义,在Python 3中,`r'...'字符串不会).
请注意,在这种特定情况下,原始字符串文字和常规字符串之间没有区别!你可以使用:
_eng_word = u"[a-zA-Z][a-zA-Z0-9'.]*"
Run Code Online (Sandbox Code Playgroud)
它将在Python 2和3中都有效.
对于原始字符串文字很重要的情况,您可以从Python 2 解码原始字符串raw_unicode_escape,捕获AttributeErrorPython 3:
_eng_word = r"[a-zA-Z][a-zA-Z0-9'.]*"
try:
# Python 2
_eng_word = _eng_word.decode('raw_unicode_escape')
except AttributeError:
# Python 3
pass
Run Code Online (Sandbox Code Playgroud)
如果你正在写的Python 3代码只(所以不必对Python的2跑了),只是下降的u全部:
_eng_word = r"[a-zA-Z][a-zA-Z0-9'.]*"
Run Code Online (Sandbox Code Playgroud)
下表比较了 Python 2(.7) 和 3(.4+) 中的(一些)不同的字符串字面量前缀:

如您所见,在 Python 3 中,没有办法让文字不处理转义,但可以处理 unicode 文字。要使用适用于 Python 2 和 3 的代码获取这样的字符串,请使用:
br"[a-zA-Z][a-zA-Z0-9'.]*".decode('raw_unicode_escape')
Run Code Online (Sandbox Code Playgroud)
实际上,您的示例不是很好,因为它没有任何 unicode 文字或转义序列。一个更好的例子是:
br"[\u03b1-\u03c9\u0391-\u03a9][\t'.]*".decode('raw_unicode_escape')
Run Code Online (Sandbox Code Playgroud)
在蟒蛇 2 中:
>>> br"[\u03b1-\u03c9\u0391-\u03a9][\t'.]*".decode('raw_unicode_escape')
u"[\u03b1-\u03c9\u0391-\u03a9][\\t'.]*"
Run Code Online (Sandbox Code Playgroud)
在 Python 3 中:
>>> br"[\u03b1-\u03c9\u0391-\u03a9][\t'.]*".decode('raw_unicode_escape')
"[?-??-?][\\t'.]*"
Run Code Online (Sandbox Code Playgroud)
这真的是一回事。