Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用编码的unicode字符串时,字符串格式错误_Python_Unicode - Fatal编程技术网

Python 使用编码的unicode字符串时,字符串格式错误

Python 使用编码的unicode字符串时,字符串格式错误,python,unicode,Python,Unicode,我正在处理一些unicode字符串,每当需要显示它们时,我都会使用utf-8对其进行编码。通过这种方式,我确保即使在将脚本的输出重定向到文件时,也使用了正确的编码(我知道还有其他方法可以做到这一点,但这不是重点) 现在,有时我需要将一些数据制成表格,为此我使用格式说明符,如下所示: def tabulate(uni1, uni2): print "%-15s,%-15s" % (uni1.encode('utf-8'), uni2.encode('utf-8')) print '012

我正在处理一些unicode字符串,每当需要显示它们时,我都会使用utf-8对其进行编码。通过这种方式,我确保即使在将脚本的输出重定向到文件时,也使用了正确的编码(我知道还有其他方法可以做到这一点,但这不是重点)

现在,有时我需要将一些数据制成表格,为此我使用格式说明符,如下所示:

def tabulate(uni1, uni2):
    print "%-15s,%-15s" % (uni1.encode('utf-8'), uni2.encode('utf-8'))

print '01234567890123456789' # ruler
tabulate(u'HELLO', u'BYE')
tabulate(u'ñññññ', u'BYE')
此程序将产生以下输出

01234567890123456789
HELLO          ,BYE            
ñññññ     ,BYE
如您所见,第二个字符串没有正确地制表。我猜
%s
不知道字符串的编码,并且计算长度很糟糕


有解决此问题的方法吗?

将格式设置为unicode,然后进行编码。

以下是Ignacio指出的实现,即在编码之前进行格式化:

def tabulate(uni1, uni2):
    print (u"%-15s,%-15s" % (uni1, uni2)).encode('utf-8')

>>> tabulate(u'HELLO', u'BYE')
HELLO          ,BYE            
>>> tabulate(u'ñññññ', u'BYE')
ñññññ          ,BYE