使用 Python 3 无法识别 Python 2 字符串表达式 [英] Python 2 string expression not recognised using Python 3

查看:47
本文介绍了使用 Python 3 无法识别 Python 2 字符串表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含这个正则表达式的 python 脚本:

I have a python script containing this regex:

expression1 = ur'(.*?),\s(.*)\s(sold(?: post-exercise)?|bought|purchased|awarded|exercised|transferred in|transferred out|re-invested)\s*([\d,]*).*price of\s*(\d*.\d+?p)'

Python 解析器 barfs 并抱怨其无效的语法.

Python parser barfs and complains its invalid Syntax.

为什么此语法在 Python 3 中无效,而在 Python 2 中有效.有没有一种方法可以编写它以同时使用两个版本?

Why is this invalid syntax in Python 3, yet valid in Python 2. Is there a way I can write it to work with both versions?

推荐答案

Python 2 ur 字符串与 Python 3 存在奇怪的不兼容,其中 \u\U 转义仍然会被处理而不是被留下原始".当 u 前缀在 3.3 修订版中重新引入 Python 3 时,明确决定是为了排除ur组合,而不是有不一致的行为.

Python 2 ur strings had a weird incompatibility with Python 3, where \u and \U escapes would still be processed instead of being left "raw". When the u prefix was reintroduced to Python 3 in the 3.3 revision, an explicit decision was made to exclude the ur combination, rather than have inconsistent behavior.

如果您想要一个在 Python 2 和 3 中都可以使用的原始 Unicode 字符串,您需要一个解决方法.可能性包括使用 br 原始字节串并使用适当的编解码器将其转换为 Unicode,或使用 from __future__ import unicode_literals 并使用普通的 r 前缀.小心 \u\U 转义.

If you want a raw Unicode string that works in both Python 2 and 3, you'll need a workaround. Possibilities include using a br raw bytestring and converting it to Unicode with an appropriate codec, or using from __future__ import unicode_literals and using the plain r prefix. Be careful about \u and \U escapes.

这篇关于使用 Python 3 无法识别 Python 2 字符串表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆