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

Let's pretend 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 execute n.encode('utf8') , it works.

The second works flawlessly 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 the documentation recommends using format() instead of the % format operator, I don’t understand why format() seems more like a handicap. Does format() only with utf8 strings?

+7
source share
1 answer

You are using string.format , while you have no string, but unicode .

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

will work as it uses unicode.format .

+10
source

All Articles