我正在尝试使用Unicode变量进行字符串格式化。例如:
您可以看到我有一个unicode字符串,它可以正常打印。问题是当我使用Python的新(和改进?)
您有任何想法为什么会发生这种情况吗?我正在使用Python 2.7.2。
>>> x = u"Some text—with an emdash."
>>> x
u'Some text\u2014with an emdash.'
>>> print(x)
Some text—with an emdash.
>>> s = "{}".format(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2014' in position 9: ordinal not in range(128)
>>> t = "%s" %x
>>> t
u'Some text\u2014with an emdash.'
>>> print(t)
Some text—with an emdash.
您可以看到我有一个unicode字符串,它可以正常打印。问题是当我使用Python的新(和改进?)
format()
函数时,就会出现问题。如果我使用旧的样式(使用%s
),一切都正常,但当我使用{}
和format()
函数时,它会失败。您有任何想法为什么会发生这种情况吗?我正在使用Python 2.7.2。