printf field width doesn't support multibyte characters?

前端 未结 6 449
孤独总比滥情好
孤独总比滥情好 2021-01-15 04:21

I want printf to recognize multi-byte characters when calculating the field width so that columns line up properly... I can\'t find an answer to this problem and was wonderi

6条回答
  •  终归单人心
    2021-01-15 04:53

    A language like python will probably solve your problems in a simpler, more controllable way...

    #!/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))
    

提交回复
热议问题