Python字符串格式化+ UTF-8奇怪的行为

Ada*_*tan 3 python string utf-8

打印具有固定长度(例如%20s)的格式化字符串时,宽度不同于UTF-8字符串与普通字符串:

>>> str1="Adam Matan"
>>> str2="??? ???"
>>> print "X %20s X" % str1
X           Adam Matan X
>>> print "X %20s X" % str2
X        ??? ??? X
Run Code Online (Sandbox Code Playgroud)

注意区别:

X           Adam Matan X
X        ??? ??? X
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

tgh*_*ghw 7

您需要通过放在u字符串前面来指定第二个字符串是Unicode :

>>> str1="Adam Matan"
>>> str2=u"??? ???"
>>> print "X %20s X" % str1
X           Adam Matan X
>>> print "X %20s X" % str2
X              ??? ??? X
Run Code Online (Sandbox Code Playgroud)

这样做可以让Python知道它正在计算Unicode字符,而不仅仅是字节.