Python String format width wrong when characters like é or ö in the string

北城以北 提交于 2019-12-12 04:57:29

问题


Using simple field width specifier, the columns are 'thinner' when the string includes 'European' characters. I have a small script to print out various fields from a Django DB (last_name, first_name, email etc), and the columns are 1 character less for each such character in the string

example:

         Johansen
       lövström

Printed using "%20s" % field.encode('utf-8')

Any ideas whats going on?? (and how to fix)


回答1:


Well, ö encodes as two bytes in UTF-8. And your format specifies 20 bytes.

You could try to format while still in the unicode string world, where %20s would mean 20 characters, and convert the formatted result to utf-8.



来源:https://stackoverflow.com/questions/9990988/python-string-format-width-wrong-when-characters-like-%c3%a9-or-%c3%b6-in-the-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!