Python:在 Unicode 转义字符串上使用 .format() [英] Python: Using .format() on a Unicode-escaped string

查看:62
本文介绍了Python:在 Unicode 转义字符串上使用 .format()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Python 2.6.5.我的代码需要使用大于或等于"符号.在这里:

<预><代码>>>>s = u'\u2265'>>>印刷>>>≥>>>打印{0}".format(s)回溯(最近一次调用最后一次):文件<input>",第 1 行,在 <module> 中UnicodeEncodeError: 'ascii' 编解码器无法编码字符 u'\u2265'在位置 0:序号不在范围内(128)`

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

解决方案

只需将第二个字符串也设为 unicode 字符串

<预><代码>>>>s = u'\u2265'>>>印刷≥>>>打印{0}".format(s)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>UnicodeEncodeError: 'ascii' 编解码器无法对位置 0 中的字符 u'\u2265' 进行编码:序号不在范围内 (128)>>>打印 u"{0}".format(s)≥>>>

I am using Python 2.6.5. My code requires the use of the "more than or equal to" sign. Here it goes:

>>> 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)`  

Why do I get this error? Is there a right way to do this? I need to use the .format() function.

解决方案

Just make the second string also a unicode string

>>> 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)
≥
>>> 

这篇关于Python:在 Unicode 转义字符串上使用 .format()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆