【问题标题】:Is there a difference between `%`-format operator and `str.format()` in python regarding unicode and utf-8 encoding?关于 unicode 和 utf-8 编码,python 中的 `%`-format 运算符和 `str.format()` 有区别吗?
【发布时间】:2011-12-22 11:37:08
【问题描述】:

假设

n = u"Tübingen"
repr(n) # `T\xfcbingen` # Unicode
i = 1 # integer

以下文件中的第一个抛出

UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 82: ordinal not in range(128)

当我执行n.encode('utf8') 时,它会起作用。

第二个在这两种情况下都完美无缺。

# Python File 1
#
#!/usr/bin/env python -B
# encoding: utf-8

print '{id}, {name}'.format(id=i, name=n)

# Python File 2
#
#!/usr/bin/env python -B
# encoding: utf-8

print '%i, %s'% (i, n)

由于在文档中鼓励使用format() 而不是% 格式运算符,我不明白为什么format() 似乎更“残障”。 format() 是否仅适用于 utf8-strings?

【问题讨论】:

  • 当你做u'{id}, {name}'.format(id=i, name=n)时你观察到了什么?请注意,格式化字符串是一个 Unicode 字符串 u'...'。请将其添加到您的示例中并对其发表评论。
  • 谢谢 S.Lott,就是这样。我现在明白我的错在哪里了。 '{id}, {name}' 是一个 utf-8 字符串(由 magic line # encoding: utf-8 定义),n 是 unicode。不可能“连接”它们。这就是n.encode('utf8') 工作的原因。对吗?

标签: python string encoding string-formatting


【解决方案1】:

您使用的是string.format,而您没有字符串而是unicode 对象。

print u'{id}, {name}'.format(id=i, name=n)

会起作用,因为它改用unicode.format

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 2013-05-11
    • 2018-01-14
    • 1970-01-01
    • 2011-04-26
    • 2013-09-11
    • 2013-08-27
    • 1970-01-01
    相关资源
    最近更新 更多