2011-12-22 4 views
7

unicodeとutf-8エンコーディングに関するpythonの `%` -format演算子と `str.format()`の違いはありますか?

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

次のファイルの最初は、私はn.encode('utf8')を行うと、それが動作

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

をスローすることを想定します。

2番目のケースでは、両方のケースで完全に機能します。

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

マニュアルに%フォーマット演算子の代わりにformat()を使用することが推奨されているのでformat()がより「handicaped」と思われる理由を、私は理解していません。 format()utf8ストリングのみで動作しますか?

+0

'' {id}、{name} '。format(id = i、name = n) 'あなたは何を観察しましたか?書式設定文字列はUnicode文字列 'u '...''であることに注意してください。それをあなたの例に加えてコメントしてください。 –

+0

ありがとうございました.Slott、これでした。私は今どこにいるのか分かっています。 '' {id}、{name} ''はutf-8文字列(*魔法行*'#encoding:utf-8'で定義されていました)であり、 'n'はユニコードです。それらを「連結」することはできません。そのため、n.encode( 'utf8')が働いたのです。右? – Aufwind

答えて

10

string.formatを使用していますが、文字列を持たずにunicodeオブジェクトを使用しています。

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

が代わりにunicode.formatを使用するため動作します。