How to control padding of Unicode string containing east Asia characters

后端 未结 6 902
灰色年华
灰色年华 2020-12-03 12:00

I got three UTF-8 stings:

hello, world
hello, 世界
hello, 世rld

I only want the first 10 ascii-char-width so that the bracket in one column:

6条回答
  •  攒了一身酷
    2020-12-03 12:49

    if you are working with English and Chinese characters, maybe this snippet can help you.

    data = '''\
    蝴蝶(A song)
    心之城(Another song)
    支持你的爱人(Yet another song)
    根生的种子
    鸽子歌(Cucurrucucu palo whatever)
    林地之间
    蓝光
    在你眼里
    肖邦离别曲
    西行(魔戒王者再临主题曲)(Into something)
    深陷爱河
    钟爱大地
    时光流逝
    卡农
    舒伯特小夜曲(SERENADE)
    甜蜜的摇篮曲(Sweet Lullaby)'''
    
    width = 80
    
    def get_aligned_string(string,width):
        string = "{:{width}}".format(string,width=width)
        bts = bytes(string,'utf-8')
        string = str(bts[0:width],encoding='utf-8',errors='backslashreplace')
        new_width = len(string) + int((width - len(string))/2)
        if new_width!=0:
            string = '{:{width}}'.format(str(string),width=new_width)
        return string
    
    for i,line in enumerate(data.split('\n')):
        song = get_aligned_string(line,width)
        line = '|{:4}: {:}|'.format(i+1,song)
        print(line)
    

    Output

提交回复
热议问题