【问题标题】:Print format unicode list [duplicate]打印格式unicode列表[重复]
【发布时间】:2018-10-10 22:20:21
【问题描述】:

我有一个 Python 2.7 中的 unicode 对象列表。我想格式化一个打印该列表的打印语句。

unicode_list = [u'something', u'\u25ba']
print u'Unicode list %s' % unicode_list

上面的代码打印Unicode list [u'something', u'\u25ba']

但是

print unicode_list[1]

按预期打印

如何正确格式化字符串以打印 unicode 列表?像这样:Unicode list ['something', '►']

【问题讨论】:

  • 我不认为我的问题是重复的。这如何解决我的问题?
  • 是的,好吧,我可能误解了这个问题。你想得到什么输出?
  • 我同意,这个问题不是重复的。在更有用的注释中,您似乎遇到了__str____repr__ 之间的区别。试试print '[%s]' % u', '.join(unicode_list)
  • @PatrickHaugh 这对我有用,您可以将其添加为答案。
  • 升级到 Python 3,你的“问题”就会神奇地消失。

标签: python python-2.7 unicode


【解决方案1】:

问题是你的字符串格式中的“%s”需要一个字符串,而你给了它一个列表。它会在插入之前将整个列表折叠成一个字符串。

我发现使用连接从列表中创建字符串更容易:

print "Unicode list ['%s']" % u"', '".join(unicode_list)

【讨论】:

  • 你需要 u。这是一个 unicode 列表。
  • 我认为您不需要在连接字符串之前使用 u,因为它已经在列表项中。 Patrick Haugh 提供了一条评论,其中包含括号和引号。我会将其添加到我的答案中。
  • 不,不要混合使用 unicode 和字符串。前缀和连接字符串也应该是 unicode 字符串。
猜你喜欢
  • 1970-01-01
  • 2019-10-28
  • 2014-01-02
  • 2021-12-31
  • 1970-01-01
  • 2010-09-21
  • 2013-10-24
  • 2019-05-01
相关资源
最近更新 更多