Auf*_*ind 7 python string encoding string-formatting
假使,假设
n = u"Tübingen"
repr(n) # `T\xfcbingen` # Unicode
i = 1 # integer
Run Code Online (Sandbox Code Playgroud)
抛出以下第一个文件
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 82: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
当我这样做的n.encode('utf8')时候.
第二种方法在两种情况下都完美无瑕.
# Python File 1
#
#!/usr/bin/env python -B
# encoding: utf-8
print '{id}, {name}'.format(id=i, name=n)
Run Code Online (Sandbox Code Playgroud)
# Python File 2
#
#!/usr/bin/env python -B
# encoding: utf-8
print '%i, %s'% (i, n)
Run Code Online (Sandbox Code Playgroud)
由于在文档中鼓励使用format()而不是%格式运算符,我不明白为什么format()看起来更"残缺".难道format()只能用工作utf8-strings?
Tom*_*rdt 10
string.format当你没有字符串而是unicode对象时,你正在使用.
print u'{id}, {name}'.format(id=i, name=n)
Run Code Online (Sandbox Code Playgroud)
将起作用,因为它使用了unicode.format.
| 归档时间: |
|
| 查看次数: |
670 次 |
| 最近记录: |