gpt4 book ai didi

Python 2.7 - 为什么 python 在列表中使用 .append() 时对字符串进行编码?

转载 作者:太空狗 更新时间:2023-10-29 22:15:37 25 4
gpt4 key购买 nike

我的问题字符串

# -*- coding: utf-8 -*-
print ("################################")
foo = "СТ142Н.0000"
print (type(foo))
print("foo: "+foo)
foo_l = []
foo_l.append(foo)
print ("List: " )
print (foo_l)
print ("List decode: ")
print([x.decode("UTF-8") for x in foo_l])
print("Pop: "+foo_l.pop())

打印结果:

################################
<type 'str'>
foo: СТ142Н.0000
List:
['\xd0\xa1\xd0\xa2142\xd0\x9d.0000']
List decode:
[u'\u0421\u0422142\u041d.0000']
Pop: СТ142Н.0000

这个工作正常,我只是用键盘手动输入字符串“CT142H.0000”(它是相同的代码)

print ("################################")
foo = "CT142H.0000"
print(type(foo))
print("foo: "+foo)
foo_l = []
foo_l.append(foo)
print ("List: ")
print (foo_l)
print ("List decode: ")
print([x.decode("UTF-8") for x in foo_l])
print("Pop: "+foo_l.pop())

打印结果:

################################
<type 'str'>
foo: CT142H.0000
List:
['CT142H.0000']
List decode:
[u'CT142H.0000']
Pop: CT142H.0000

当我将第一个字符串追加到列表中时,为什么 python 会对第一个字符串进行编码?

--------------------------------------------

目前已解决,我担心那是字符,我将“结果”放入 JSON 中,然后放入网站中,最后在网站中运行正常!

--------------------------------------------

我找到了另一个解决方案,但没有一个是正确的解决方案,因为在某些情况下你会遇到问题。

json.dumps(list, ensure_ascii=False)

谢谢大家!

最佳答案

因为即使它们看起来像普通的 C/T/H 字符,但它们实际上不是那些字符。

它们是西里尔字符。

С - Cyrillic Capital letter ES
Т - Cyrillic Capital letter TE
Н - Cyrillic Capital letter EN

您需要检查从哪里获得这些字符,以及它们为何如此。

关于为什么使用 \x.. 表示打印它们,是因为当您打印 list 时, __str__() 方法on list 被调用,但 list 本身在其元素上调用 __repr__() ,因此您获得了字符串的内部表示。如果你这样做,你会得到类似的结果 -

print(repr(foo))

对于第一种情况。

关于Python 2.7 - 为什么 python 在列表中使用 .append() 时对字符串进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32007092/

25 4 0
文章推荐: c# - 无法从 'method group' 转换为 'ResumeAfter'