首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python:在Unicode转义的字符串上使用.format()

Python:在Unicode转义的字符串上使用.format()
EN

Stack Overflow用户
提问于 2010-07-13 16:29:13
回答 2查看 99.4K关注 0票数 159

我使用的是Python 2.6.5。我的代码需要使用“大于或等于”符号。它是这样的:

代码语言:javascript
复制
>>> s = u'\u2265'
>>> print s
>>> ≥
>>> print "{0}".format(s)
Traceback (most recent call last):
     File "<input>", line 1, in <module> 
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2265'
  in position 0: ordinal not in range(128)`  

为什么会出现这个错误?有没有正确的方法来做这件事?我需要使用.format()函数。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-07-13 16:34:48

只需使第二个字符串也是unicode字符串

代码语言:javascript
复制
>>> s = u'\u2265'
>>> print s
≥
>>> print "{0}".format(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2265' in position 0: ordinal not in range(128)
>>> print u"{0}".format(s)
≥
>>> 
票数 247
EN

Stack Overflow用户

发布于 2010-07-13 16:35:36

unicode%s需要unicode格式的字符串。

代码语言:javascript
复制
>>> print u'{0}'.format(s)
≥
票数 71
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3235386

复制
相关文章

相似问题

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