背景
- 列表中多个字符串的内容格式不统一, 有纯中,纯英,也有中英混合。
- 使用python自带函数 str.rjust等时,出现无法对齐现象
- win10, anaconda 4.8.3, python 3.8.3
办法
- 计算各字符串的中、英单字符数量,进行调整
- 具体见代码
- 填充字符(填充空格保持长度的字符)暂只支持单字节字符
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 (零), 暂不支持非英文或非单字节字符'''
def getLen(strchk):
strlen = 0
for letter in strchk:
if ord(letter) > 255:
strlen += 2
else:
strlen += 1
return strlen
def newrlcjust(listchk, ttllength, direction ='r', fillwith = '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__':
test()