【问题标题】:Python encoding: list to string having special characters and numbers in the listPython编码:列表中包含特殊字符和数字的字符串
【发布时间】:2013-06-11 09:05:15
【问题描述】:

我需要加入这样的事情:

["Círculo", 23]
["Triángulo, 25, 19, "dos"]

我看过这个帖子 -> Joining a list that has Integer values with Python

但解决方案如下:

', '.join(map(str, myList)) or ', '.join(str(x) for x in list_of_ints)

对我不起作用,因为特殊字符 'í' 使其失败:

UnicodeEncodeError: 'ascii' codec can't encode character ... in 位置...:序数不在范围内(128)

那么解决它的pythonic方法是什么?我不想检查类型... 谢谢!

【问题讨论】:

  • 你能将列表元素定义为 unicode 吗?像这样 [u'Círculo', 23] 它将使用@Blubber 的答案解决您的问题
  • 如果可能的话,我想避免它。编辑:不,我不能:(

标签: python unicode encoding


【解决方案1】:

检查编码我找到了适合我的解决方案:

 u', '.join([unicode(x.decode('utf-8')) if type(x) == type(str()) else unicode(x) for x in a])

诀窍是使用decode('utf-8') 获取字符的有效 8 位表示。

希望这会有所帮助。

【讨论】:

  • 谢谢@Ander2,我不想使用类型检查,但看起来这是唯一的方法......谢谢很多
【解决方案2】:
import encodings

a=encodings.utf_16.decode(a[0])
encodings.utf_16.encode(a[0])

您是否尝试过使用 encodings 模块?也许你会得到它来处理这个。 但似乎不适用于 utf_16 编码...

【讨论】:

    【解决方案3】:

    如果您可以将列表中的字符串指定为 unicode,例如:

    [u"Círculo", 23]
    [u"Triángulo", 25, 19, u"dos"]
    

    那么这应该可以工作:

    u', '.join(unicode(x) for x in list_of_ints)
    

    假设您正在运行 Python 2。

    【讨论】:

    • 这只有在您假设@Ander2 评论时才有效。更新回复,我会将其标记为已接受:)
    猜你喜欢
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 2022-07-16
    相关资源
    最近更新 更多