Python utf-8, howto align printout

前端 未结 3 2227
悲哀的现实
悲哀的现实 2021-01-02 15:20

I have a array containing japanese caracters as well as \"normal\". How do I align the printout of these?

#!/usr/bin/python
# coding=utf-8

a1=[\'する\', \'します         


        
3条回答
  •  孤独总比滥情好
    2021-01-02 15:50

    Using the unicodedata.east_asian_width function, keep track of which characters are narrow and wide when computing the length of the string.

    #!/usr/bin/python
    # coding=utf-8
    
    import sys
    import codecs
    import unicodedata
    
    out = codecs.getwriter('utf-8')(sys.stdout)
    
    def width(string):
        return sum(1+(unicodedata.east_asian_width(c) in "WF")
            for c in string)
    
    a1=[u'する', u'します', u'trazan', u'した', u'しました']
    a2=[u'dipsy', u'laa-laa', u'banarne', u'po', u'tinky winky']
    
    for i,j in zip(a1,a2):
        out.write('%s %s: %s\n' % (i, ' '*(12-width(i)), j))
    

    Outputs:

    する          : dipsy
    します        : laa-laa
    trazan        : banarne
    した          : po
    しました      : tinky winky
    

    It doesn’t look right in some web browser fonts, but in a terminal window they line up properly.

提交回复
热议问题