How to do string formatting with unicode emdash?

五迷三道 提交于 2019-12-07 05:51:13

问题


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.


回答1:


The new format() is not as forgiving when you mix ASCII and unicode strings ... so try this:

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



回答2:


The same way.

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



回答3:


Using the following worked well for me. It is a variant on the other answers.

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


来源:https://stackoverflow.com/questions/8152820/how-to-do-string-formatting-with-unicode-emdash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!