在Python 2.7中使用格式填充和证明多字节Unicode字符串

时间:2015-10-15 05:15:54

标签: python string python-2.7 unicode

在Python中,它很容易填充(即填充)字符串,并使用string.format向左,向右或居中对齐。例如:

>>> word = "Resume"
>>> print "123456890\n{0:>{1}}".format(word, 10)
>>> print len(name)

1234567890
    Resume
6    

但是,如果字符串包含多字节Unicode字符,string.format无法正确计算字符串的宽度:

>>> word = u"Résumé"
>>> print "123456890\n{0:>{1}}".format(word.encode('utf8'), 10)
>>> print len(name.encode('utf8'))

1234567890
  Résumé
8

解决方案是使用unicodedata.normalize('NFC', string),您可能已阅读过。这确实是normalize Unicode character个序列(在某些情况下也可能是必要的!)但导致string.format正确计算字符串的编码宽度以输出到a终端

那么如何在Python 2.7中使用string.format正确填充/填充字符串?

1 个答案:

答案 0 :(得分:2)

事实证明,答案很简单:使用Unicode文字格式字符串:

>>> word = u"Résumé"
>>> print u"123456890\n{0:>{1}}".format(word, 10)
>>> print len(name)

1234567890
    Résumé
6

这个单字符解决方案似乎隐藏在Python错误跟踪器上的Victor Stinner的message中:

  

哦顺便说一句,在Python 2中解决这个问题很简单:只使用Unicode格式字符串。例如,将'{0}'.format(u'\u3042')替换为u'{0}'.format(u'\u3042')

我还没有在任何StackOverflow答案或Google上的任何网页上找到此信息,无论是博客,论坛,邮件列表等等。所以现在就是这样!