首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用unicode emdash进行字符串格式化?

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

Stack Overflow用户
提问于 2011-11-16 21:58:26
回答 3查看 7.8K关注 0票数 7

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

代码语言:javascript
运行
复制
>>> 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。

EN

Stack Overflow用户

发布于 2017-06-14 15:31:29

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

代码语言:javascript
运行
复制
>>> emDash = u'\u2014'
>>> "a{0}b".format(emDash)
'a—b'
票数 3
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8152820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档