I'm attempting to make some ui tools for my python ncurses application, and I needed a word wrap function. It works pretty well, but trying to read it is frustrating. I'm specifically looking for readability improvements, but if there are some other tips you can give, including edge cases or PEP violations, they would also be appreciated.
class ui_util:
def chunk_word(word, length):
return [ word[i:i+length] for i in range(0, len(word), length) ]
def word_wrap(str, width):
def add_first_word():
nonlocal word
nonlocal wrapped_line
nonlocal lines_final
if (len(word) <= width):
wrapped_line = word
else:
chunks = ui_util.chunk_word(word, width)
for i in range(len(chunks) - 1):
lines_final.append(chunks[i])
wrapped_line = chunks[-1]
lines = str.splitlines()
lines_final = []
for line in lines:
if (len(line) <= width):
lines_final.append(line)
else:
words = line.split()
wrapped_line = ""
for word in words:
if (len(wrapped_line) == 0):
add_first_word()
elif (len(wrapped_line) + len(word) + 1 <= width):
wrapped_line += ' ' + word
else:
lines_final.append(wrapped_line)
add_first_word()
lines_final.append(wrapped_line)
return lines_final
Called like:
lines = ui_util.word_wrap("some test words 13_chars_word\r\nnew line\r\n12_char_word 13_chars_word", 12)
for i in range(len(lines)):
print(lines[i])
Output:
some test
words
13_chars_wor
d
new line
12_char_word
13_chars_wor
d
ui_util.word_wrap("13_chars_word new line", 12)yields.13_chars_word new line\$\endgroup\$textwrap.wrap? \$\endgroup\$