def strcrop(string, width, tail=None):
"""Return `string` cropped to `width`, considering wide characters
If `tail` is not None, it must be a string that is appended to the cropped
string.
"""
def widechar_indexes(s):
for i,c in enumerate(s):
if unicodedata.east_asian_width(c) in 'FW':
yield i
if strwidth(string) <= width:
return string # string is already short enough
if tail is not None:
width -= strwidth(tail) # Account for tail in final width
indexes = list(widechar_indexes(string)) + [len(string)]
if not indexes:
return string[:width] # No wide chars, regular cropping is ok
parts = []
start = 0
end = 0
currwidth = strwidth(''.join(parts))
while indexes and currwidth < width and end < len(string):
end = indexes.pop(0)
if end > 0:
parts.append(string[start:end])
currwidth = strwidth(''.join(parts))
start = end
if currwidth > width:
excess = currwidth - width
parts[-1] = parts[-1][:-excess]
if tail is not None:
parts.append(tail)
return ''.join(parts)
评论列表
文章目录