字符串对齐方法,自用,综合, newrlcjust

背景

  • 列表中多个字符串的内容格式不统一, 有纯中,纯英,也有中英混合。
  • 使用python自带函数 str.rjust等时,出现无法对齐现象
  • win10, anaconda 4.8.3, python 3.8.3

办法

  • 计算各字符串的中、英单字符数量,进行调整
  • 具体见代码
  • 填充字符(填充空格保持长度的字符)暂只支持单字节字符
#
#  纯英文, 纯中文, 英中混合字符串组成的列表(list)内容进行对齐: 右, 左, 中
#  导入后, 运行 chn_en_alignment.test() 查看如何使用
#  导入后, 运行 chn_en_alignment.newrlcjust(listchk, ttllength, direction ='r', fillwith = '0')
#  或 import chn_en_alignment.newrlcjust as rlcjust, 再按照 rlcjust('上述参数顺序') 运行
#  V1, 20201016
#


#  data for test
list1=['abc', 'a', 'abcded', 'aa']
list2=['中芯', '台积电', '华为科技']
list3=['NXP', '中芯', '台积电']
list4=['NXP', '中芯', 'Huawei科技']
list5=['123', '中"芯"', '华Hua为Wei']


usage='''
Usage:
newrlcjust(listchk, ttllength, direction ='r', fillwith = '0')
listchk: 字符串元素 list, 待检查
ttllength: 整数, list中所有字串对齐的宽度要求,
ttllength: 数字采用ttllength 与 list中字符转最大长度 的最大者
direction: r-right, l-left, c-center, 默认 r
fillwith: 用什么填充空位(如果有), 默认 0 (零), 暂不支持非英文或非单字节字符'''


#  chn =2, en=1, return additional len
def getLen(strchk):
    #  get total length, chn calculated as 2, en as 1
    strlen = 0
    for letter in strchk:
        #  print(letter, flush=True)
        if ord(letter) > 255:
            strlen += 2
        else:
            strlen += 1
    return strlen


def newrlcjust(listchk, ttllength, direction ='r', fillwith = '0'):
    #  listchk: list with elements to be aligned;
    #  ttllength: total length you see after output;
    #  direction, default as 'r', one of the three 'r', or 'l', or 'c',
    #  fillwith, default as '0';

    listchkLenmax=max(getLen(x) for x in listchk)
    for strchk in listchk:
        difflength = 0
        if ttllength > listchkLenmax:
            listchkLenmax = ttllength
        ttl = listchkLenmax - (getLen(strchk)-len(strchk))

        if direction == 'r':
            print(strchk.rjust(ttl, fillwith))
        elif direction == 'l':
            print(strchk.ljust(ttl, fillwith))
        else:
            print(strchk.center(ttl, fillwith))


def test():

    print('\n中文计位2个宽度, 英文计位1个宽度.')
    print('len(str)把中、英文的单个部分,均计位长度 1')
    print(usage)
    print( "*" * 66, '\n')
    print('following are examples: \n')
    i_sequence = 0
    for lst in [list1, list2, list3, list4, list5]:
        print('lst:',lst)
        direction=['r','l','c'][i_sequence]
        print("example as: newrlcjust(lst, ttllength=1, direction ='" +direction + "', fillwith = '0')")
        newrlcjust(lst, ttllength=1, direction =direction, fillwith = '0')
        print('\n')
        i_sequence += 1
        i_sequence = i_sequence % 3


if __name__ == '__main__':
    #  newrlcjust(list4, 20, direction ='r', fillwith = '…')
    # fill的 … ,中文输入法下 shift + 6, 再backspace一次. powershell下无法输入
    test()

猜你喜欢

转载自blog.csdn.net/seeker3/article/details/109129611