简体   繁体   English

这是unicode还是str?

[英]Is this a unicode or a str?

I have a dictionary that I need to share from Python 3 to Python 2. I dumped it as JSON in P3 and then loaded in Python2. 我有一个字典,需要从Python 3共享到Python2。我将其作为JSON转储到P3中,然后加载到Python2中。 Finally I (thought I) converted to P2 string using yaml.load . 最后,我(认为是我)使用yaml.load转换为P2字符串。

Now there is something that seems wrong to me. 现在有些事情对我来说似乎是错误的。 I know that there are some unicode string(s) that are breaking a package. 我知道有些unicode字符串正在破坏包装。 I tried to find them using 我试图用找到

[key  for key in my_dict if type(key) != str]
[] 

Why then 那为什么

'C%2B%2B' in my_dict
True

and

type('C%2B%2B')
unicode

is not caught? 没抓到? Why does the list comprehension think it is a string? 为什么列表理解认为它是一个字符串?

[type(key)  for key in my_dict if key == 'C%2B%2B']
[str]

Finally, is there a way I can convert it to str so that it will not break my code? 最后,有没有一种方法可以将其转换为str,从而不会破坏我的代码?

EDIT: ipython2 seems to have no consistent behavior on my computer: 编辑:ipython2在我的计算机上似乎没有一致的行为:

在此处输入图片说明

vs

在此处输入图片说明

You must keep control over your data before encoding it to JSON. 您必须先控制数据,然后再将其编码为JSON。 In Python 3, make sure all of the strings are unicode objects (ie of type str ), and then write them to a JSON file using eg UTF-8 encoding. 在Python 3中,确保所有字符串都是unicode对象(即str类型),然后使用例如UTF-8编码将它们写入JSON文件。 Then decode that file using the same codec in Python 2. The resulting string types must be unicode . 然后在Python 2中使用相同的编解码器对该文件进行解码。结果字符串类型必须是unicode The code snippets you are showing do not help much, it is unclear in which version of Python you executed each of the snippets shown (the type('C%2B%2B') == unicode case suggests that you are using Python 2 with from __future__ import unicode_literals , the last snippet, however, is likely created from within Python 3). 您显示的代码片段并没有多大帮助,目前尚不清楚您在哪个版本的Python中执行了所示的每个片段( type('C%2B%2B') == unicode情况表明您正在使用Python 2, from __future__ import unicode_literals ,最后一个代码段可能是在Python 3中创建的。 You must understand that type str in Python 2 is fundamentally different from str in Python 3. 必须了解Python 2中的类型str与Python 3中的str根本不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM