|
发表于 2018-4-3 10:58:53
|
显示全部楼层
1. 获取字符串宽度
- def get_str_width(string):
- widths = [
- (126, 1), (159, 0), (687, 1), (710, 0), (711, 1),
- (727, 0), (733, 1), (879, 0), (1154, 1), (1161, 0),
- (4347, 1), (4447, 2), (7467, 1), (7521, 0), (8369, 1),
- (8426, 0), (9000, 1), (9002, 2), (11021, 1), (12350, 2),
- (12351, 1), (12438, 2), (12442, 0), (19893, 2), (19967, 1),
- (55203, 2), (63743, 1), (64106, 2), (65039, 1), (65059, 0),
- (65131, 2), (65279, 1), (65376, 2), (65500, 1), (65510, 2),
- (120831, 1), (262141, 2), (1114109, 1),
- ]
- width = 0
- for each in string:
- if ord(each) == 0xe or ord(each) == 0xf:
- each_width = 0
- continue
- elif ord(each) <= 1114109:
- for num, wid in widths:
- if ord(each) <= num:
- each_width = wid
- width += each_width
- break
- continue
- else:
- each_width = 1
- width += each_width
- return width
复制代码
2. 返回宽度对齐的字符串(需指定总宽度)
- def align_string(string, width):
- string_width = get_str_width(string)
- if width > string_width:
- return string+' '*(width-string_width)
- else:
- return string
复制代码- s1 = '一个长句子abcdef'
- s2 = '短句子123'
- print(align_string(s1, 20) + align_string(s2, 18))
- print(align_string(s2, 20) + align_string(s1, 18))
复制代码
结果:
- 一个长句子abcdef 短句子123
- 短句子123 一个长句子abcdef
复制代码
|
|