Python:在单*度转义字符串上使用.format()

时间:2022-12-20 20:12:59

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

我使用的是Python 2.6.5。我的代码要求使用“more than or equal”符号。这里是:

>>> 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.

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

2 个解决方案

#1


211  

Just make the second string also a unicode string

让第二个字符串也是unicode字符串

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

#2


57  

unicodes need unicode format strings.

unicodes需要unicode格式的字符串。

>>> print u'{0}'.format(s)
≥

#1


211  

Just make the second string also a unicode string

让第二个字符串也是unicode字符串

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

#2


57  

unicodes need unicode format strings.

unicodes需要unicode格式的字符串。

>>> print u'{0}'.format(s)
≥