![](/img/trans.png)
[英]How can I find the key in a dict whose matching value, which is a list, contains X?
[英]How to encode object like list of dict which contains unicode key or value to utf8?
有什么簡單的方法可以將包含unicode字符串的對象轉換為utf8?
例如:
before = [
u'labelset': {u'labelset_id': 80L, u'labelset_name': u'\u6d17\u8863\u6a5f'},
u'labelset': {u'labelset_id': 81L, u'labelset_name': u'\u6d17\u8863\u6a5f'},
u'labelset': {u'labelset_id': 82L, u'labelset_name': u'\u6d17\u8863\u6a5f'},
]
after = [
'labelset': {labelset_id: 80L, labelset_name: 'test'},
'labelset': {labelset_id: 81L, labelset_name: 'test'},
'labelset': {labelset_id: 81L, labelset_name: 'test'},
]
在python 2. *中,有兩種類型的字符串:
str (sequence of bytes)
unicode (sequence of unicode code points)
要將unicode轉換為str,需要指定規則(哪些字節代表特定的unicode點)。 此規則稱為編碼 。 因此,改造的unicode為str,使用utf8
編碼,您需要使用encode
方法:
>>> u'\u6d17\u8863\u6a5f'.encode('utf8')
'\xe6\xb4\x97\xe8\xa1\xa3\xe6\xa9\x9f'
結果將是一個字節序列,可以將其保存到例如文本文件中。
要將str轉換回unicode,您需要知道在從unicode轉換到str的過程中應用了哪些規則。 在當前情況下,此規則是utf8
編碼。 為此,請使用decode
方法:
>>> '\xe6\xb4\x97\xe8\xa1\xa3\xe6\xa9\x9f'.decode('utf8')
u'\u6d17\u8863\u6a5f'
這是有關python字符串和編碼的很好的演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.