如何使用 unicode emdash 进行字符串格式化? [英] How to do string formatting with unicode emdash?
问题描述
我正在尝试使用 unicode 变量进行字符串格式化.例如:
<预><代码>>>>x = u"一些文字——带有一个破折号.">>>Xu'一些带有 emdash 的文本\u2014.>>>打印(x)一些文本 - 带有 emdash.>>>s = "{}".format(x)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中UnicodeEncodeError: 'ascii' codec can't encode character u'\u2014' in position 9: ordinal not in range(128)>>>t = "%s" %x>>>吨u'一些带有 emdash 的文本\u2014.>>>打印(吨)一些文本 - 带有 emdash.你可以看到我有一个 unicode 字符串并且它打印得很好.问题是当我使用 Python 的新(和改进?) format()
函数时.如果我使用旧样式(使用 %s
)一切正常,但是当我使用 {}
和 format()
函数时,它失败了.
关于为什么会发生这种情况的任何想法?我使用的是 Python 2.7.2.
当你混合 ASCII 和 unicode 字符串时,新的 format()
不是那么宽容......所以试试这个:
s = u"{}".format(x)
I am trying do string formatting with a unicode variable. For example:
>>> 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.
You can see that I have a unicode string and that it prints just fine. The trouble is when I use Python's new (and improved?) format()
function. If I use the old style (using %s
) everything works out fine, but when I use {}
and the format()
function, it fails.
Any ideas of why this is happening? I am using Python 2.7.2.
The new format()
is not as forgiving when you mix ASCII and unicode strings ... so try this:
s = u"{}".format(x)
这篇关于如何使用 unicode emdash 进行字符串格式化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!