gpt4 book ai didi

python - 我如何使用 Python 字符串以使相同的代码在 2.6、2.7、3.x 中工作

转载 作者:行者123 更新时间:2023-11-28 16:42:12 25 4
gpt4 key购买 nike

我想编写一些简单的 Python 脚本,可以在不同的 Python 版本上不加修改地使用,但是我在处理字符串时遇到了问题...

text = get_data()  
phrases = [ "Soggarth Eogham O'Growney ,克尔・德怀尔", "capitis #3 病态上升涨大的繁殖性勃现", "IsoldeIsult、第一任威尔士亲王" ]
for item in phrases:
if item not in text: **# 3.3 ok. 2.7 UnicodeDecodeError**
print ("Expected phrase '" + item + "' not found")

上面的代码适用于 3.3。当我尝试在 2.7 下运行它时,我得到了

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 27: ordinal not in range(128)

这很容易通过将第一行更改为

来解决
text = get_data().encode('utf-8')

但是,这在 3.3 上不起作用。有什么方法可以使它与一个版本的源代码一起工作?Python 菜鸟。

最佳答案

get_data() 似乎会返回 Unicode 字符串。您收到错误是因为您将 Unicode 字符串与 8 位字符串连接,强制转换,默认情况下将使用 ASCII 编解码器完成转换,并且由于数据包含非 ASCII 字符,因此失败。

让上述代码工作的最佳方法是确保所有字符串都是 Unicode,方法是在它们前面加上 u"":

phrases = [ u"Soggarth Eogham O'Growney ,克尔・德怀尔", 
u"capitis #3 病态上升涨大的繁殖性勃现",
u"IsoldeIsult、第一任威尔士亲王" ]

但是,这仅适用于 Python 2.x 和 Python 3.3。如果您需要使用 Python 3.2 或 3.1,则需要有一种方法可以在 Python 2 下将其转换为 Unicode,但在 Python 3 下什么都不做(因为它已经是 Unicode)。

这样的函数通常称为u(),您可以这样定义它:

import sys
if sys.version < '3':
import codecs
def u(x):
return codecs.unicode_escape_decode(x)[0]
else:
def u(x):
return x

关于python - 我如何使用 Python 字符串以使相同的代码在 2.6、2.7、3.x 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17936029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com