gpt4 book ai didi

python - 在 python 2.X 中混合 unicode 和 str ... 问题?

转载 作者:太空宇宙 更新时间:2023-11-04 10:59:40 25 4
gpt4 key购买 nike

mystr = 'aaaa'
myvar = u'My string %s' % str(mystr)

这会成为 future 的问题吗?我弄乱了一些在 Python 中使用电子邮件模块的内部代码,并找到了一些这样的代码。 mystr 将始终只有 ascii 字符,因为它来自具有预定义的仅 ascii 字符的列表。

我没有写代码,并且有 str(mystr)mystr 不会改变问题的内容。

执行第一个片段我将拥有一个安全的 unicode 对象,或者我必须

mystr = u'aaaa'
myvar = u'My string %s' % mystr

mystr = 'aaaa'
myvar = u'My string %s' % unicode(mystr)

?

(我知道这不是正确的做法,我知道我应该处理异常,我只是在这里问第一个代码片段是否返回有效的 unicode 对象,或者 Python 是否搞砸了它的内部结构或什么时候做。)

最佳答案

尝试将实际的 unicode 符号放入字符串中(例如元音变音符号或西里尔字母),然后看输得一塌糊涂。 :)

s = 'свят' # world
v = u'здравей %s' % s # hello %s

Traceback (most recent call last):
File "<input>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 0: ordinal not in range(128)

问题是您很可能会对您的应用程序进行编码,并且在一个晴朗的日子里,一些俄罗斯人或德国人会写下她的名字,并且会突然得到一个 Internal Server Error 因为有一个非 ascii 符号以她的名义。


I know... I'm asking about the situation in my example, using ascii only in

不会,不会有问题。恕我直言,这是 Python 中的错误,因为这是错误,等待咬人。这应该是一个 fatal error ,但由于历史原因,我猜,它不是。

关于python - 在 python 2.X 中混合 unicode 和 str ... 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6737736/

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