I'm a huge fan of command line programs. Most of my programs are command line ones, they're relatively easier to use and implement without any GUI overhead. The problem is, I want my output to be perfectly aligned in the terminal. Specifically, long lines are really hard to track from the command line. There isn't anything indicating that the word is actually split in two. Even worse, when the user resizes the terminal his output will get messy and cluttered. For now, I want to solve the long lines problem, so I came up with this far from perfect function. It doesn't work .. for some reason ..
def divide_text(text, length):
string = ''
strings = []
text_length = len(text)
length_added = 0
word1 = None
num_words = len(text.split())
words_added = 0
if num_words == 1:
return [text]
for word in text.split():
while True:
if length_added + len(word) + (0 if num_words - words_added == 1 else 1 ) <= length:
if num_words == words_added + 1:
string += word
else:
string += (' ' + word) if length_added > 0 else word
length_added += len(word) + 1
words_added += 1
if word1 is not None:
word = word1
word1 = None
continue
break
elif length_added + 1 == length:
strings.append(string)
length_added = 0
string = ''
if word1 is not None:
word = word1
word1 = None
continue
break
else: # length_added + len(word) > length
length_left = length - length_added
word1 = word[length_left - 1:]
word = word[0:length_left - 1] + '-'
continue
return strings