如何在python中左对齐UTF-8编码的字符串?
我正在尝试将UTF-8编码的字符串与如何在python中左对齐UTF-8编码的字符串?,python,encoding,utf-8,format,Python,Encoding,Utf 8,Format,我正在尝试将UTF-8编码的字符串与string.ljust左对齐。引发此异常:UnicodeDecodeError:“ascii”编解码器无法解码位置0:序号不在范围(128)中的字节0xe5。比如说, s = u"你好" // a Chinese string stdout.write(s.encode("UTF-8").ljust(20)) 我走对了吗?或者我应该使用其他方法来格式化 谢谢并致以最诚挚的问候。您是否发布了您收到的确切代码和错误?因为您的代码不会在cp437和utf-
string.ljust
左对齐。引发此异常:UnicodeDecodeError:“ascii”编解码器无法解码位置0:序号不在范围(128)中的字节0xe5
。比如说,
s = u"你好" // a Chinese string
stdout.write(s.encode("UTF-8").ljust(20))
我走对了吗?或者我应该使用其他方法来格式化
谢谢并致以最诚挚的问候。您是否发布了您收到的确切代码和错误?因为您的代码不会在
cp437
和utf-8
终端上引发错误。在任何情况下,您都应该在将Unicode字符串发送到终端之前对其进行对齐。请注意差异,因为UTF-8编码的中文在编码时长度为6,而不是长度为2:
>>> sys.stdout.write(s.encode('utf-8').ljust(20) + "hello")
你好 hello
>>> sys.stdout.write(s.ljust(20).encode('utf-8') + "hello")
你好 hello
另外请注意,在典型的固定宽度字体中,汉字比其他字符宽,因此,如果混合使用不同的语言,可能仍会出现不一致的情况(有关解决方案,请参阅):
通常,您可以跳过显式编码到stdout
。Python以终端的编码方式将Unicode字符串隐式编码到终端(请参见sys.stdout.encoding
):
另一个选项是使用打印:
print "%20s" % s # old-style
或:
你有没有公布你收到的确切代码和错误?因为您的代码不会在cp437
和utf-8
终端上引发错误。在任何情况下,您都应该在将Unicode字符串发送到终端之前对其进行对齐。请注意差异,因为UTF-8编码的中文在编码时长度为6,而不是长度为2:
>>> sys.stdout.write(s.encode('utf-8').ljust(20) + "hello")
你好 hello
>>> sys.stdout.write(s.ljust(20).encode('utf-8') + "hello")
你好 hello
另外请注意,在典型的固定宽度字体中,汉字比其他字符宽,因此,如果混合使用不同的语言,可能仍会出现不一致的情况(有关解决方案,请参阅):
通常,您可以跳过显式编码到stdout
。Python以终端的编码方式将Unicode字符串隐式编码到终端(请参见sys.stdout.encoding
):
另一个选项是使用打印:
print "%20s" % s # old-style
或:
print '{:20}'.format(s) # new-style