如何使用unicode emdash进行字符串格式化?

2024-06-16 19:17:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用unicode变量进行字符串格式化。例如:

>>> 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()函数时,它失败了。

你知道为什么会这样吗?我正在使用Python2.7.2。


Tags: 函数字符串textinanformatmostwith
3条回答

使用下面的方法对我很有效。它是其他答案的变体。

>>> emDash = u'\u2014'
>>> "a{0}b".format(emDash)
'a—b'

同样的方式。

>>> s = u"{0}".format(x)
>>> s
u'Some text\u2014with an emdash.'

当您混合使用ASCII和unicode字符串时,新的format()就不那么宽容了。。。所以试试这个:

s = u"{}".format(x)

相关问题 更多 >