Is there a difference between `%`-format operator and `str.format()` in python regarding unicode and utf-8 encoding?

£可爱£侵袭症+ 提交于 2019-12-21 04:39:06

问题


Assume that

n = u"Tübingen"
repr(n) # `T\xfcbingen` # Unicode
i = 1 # integer

The first of the following files throws

UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 82: ordinal not in range(128)

When I do n.encode('utf8') it works.

The second works flawless in both cases.

# Python File 1
#
#!/usr/bin/env python -B
# encoding: utf-8

print '{id}, {name}'.format(id=i, name=n)

# Python File 2
#
#!/usr/bin/env python -B
# encoding: utf-8

print '%i, %s'% (i, n)

Since in the documentation it is encouraged to use format() instead of the % format operator, I don't understand why format() seems more "handicaped". Does format() only work with utf8-strings?


回答1:


You're using string.format while you don't have a string but an unicode object.

print u'{id}, {name}'.format(id=i, name=n)

will work, since it uses unicode.format instead.



来源:https://stackoverflow.com/questions/8603333/is-there-a-difference-between-format-operator-and-str-format-in-python-r

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