【发布时间】: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