def justify_line(line, width):
"""Stretch a line to width by filling in spaces at word gaps.
The gaps are picked randomly one-after-another, before it starts
over again.
"""
i = []
while 1:
# line not long enough already?
if len(' '.join(line)) < width:
if not i:
# index list is exhausted
# get list if indices excluding last word
i = range(max(1, len(line)-1))
# and shuffle it
random.shuffle(i)
# append space to a random word and remove its index
line[i.pop(0)] += ' '
else:
# line has reached specified width or wider
return ' '.join(line)
评论列表
文章目录