Python 删除unicode';u';从列表中
我有一张这样的清单Python 删除unicode';u';从列表中,python,list,dictionary,unicode,Python,List,Dictionary,Unicode,我有一张这样的清单 d=[{u'Length': u'2.96m', u'Width': u'1.44m', u'height': u'0.38m'}, {u'Length': u'3.8m', u'Width': u'0.65m', u'height': u'9.3m'}, {u'Length': u'0.62m', u'Width': u'2.9m', u'height': u'3.5m'}] 我想用一种简单的方法从这个列表中删除unicode'u'来创建一个新的列表。这里的“简单方法”是
d=[{u'Length': u'2.96m', u'Width': u'1.44m', u'height': u'0.38m'},
{u'Length': u'3.8m', u'Width': u'0.65m', u'height': u'9.3m'},
{u'Length': u'0.62m', u'Width': u'2.9m', u'height': u'3.5m'}]
我想用一种简单的方法从这个列表中删除unicode'u'来创建一个新的列表。这里的“简单方法”是在不导入外部模块或将其保存在外部文件的情况下删除unicode
这是我尝试过的五种方法
def to_utf8(d):
if type(d) is dict:
result = {}
for key, value in d.items():
result[to_utf8(key)] = to_utf8(value)
elif type(d) is unicode:
return d.encode('utf8')
else:
return d
#these three returns AttributeError: 'list' object has no attribute 'encode'
d.encode('utf-8')
d.encode('ascii')
d.encode("ascii","replace")
#output the same
to_utf8(d)
print str(d)
冷杉三回
AttributeError:“list”对象没有属性“encode”
最后两个打印相同的结果。我应该如何删除unicode“u”?如何,迭代列表并对字典中的每个键、值进行编码
converted = [{ str(key): str(value)
for key, value in array.items()
} for array in d]
print (converted)
您应该首先将它们编码为字节,然后将它们解码为ascii字符串
l = list()
for item in d:
temp = dict()
for key, value in item.items():
temp[key.encode("utf-8").decode("ascii")] = value.encode("utf-8").decode("ascii")
l.append(temp)
这是最简单的解决办法
d=[{u'Length': u'2.96m', u'Width': u'1.44m', u'height': u'0.38m'},
{u'Length': u'3.8m', u'Width': u'0.65m', u'height': u'9.3m'},
{u'Length': u'0.62m', u'Width': u'2.9m', u'height': u'3.5m'}]
def to_utf8(d):
final = []
for item in d:
if type(item) is dict:
result = {}
for key, value in item.items():
result[str(key)] = str(value)
final.append(result)
return final
print to_utf8(d)
可能重复使用str()函数将其转换为字符串。@JayParikh尝试了dosentwork@Eka它起作用了。看我的答案。不,这不是最简单的方法。答案更简单,至少在我的书中是这样。最好是使用
str(…)
而不是。编码('utf-8')
,因为unicode
和str
在Python 2中不是同一类型。这个答案首先使用encode(“utf-8”)
。这个答案的优点一定是列表理解。而且str
必须从已接受的答案中借用。我认为,encode(“utf-8”)。decode(“ascii”)
揭示了Python2中字符串和字节之间的关系。因为没有指定2或3。