Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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
share|improve this question

put on hold as off-topic by Jamal 17 hours ago

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions containing broken code or asking for advice about code not yet written are off-topic, as the code is not ready for review. Such questions may be suitable for Stack Overflow or Programmers. After the question has been edited to contain working code, we will consider reopening it." – Jamal
If this question can be reworded to fit the rules in the help center, please edit the question.

    
The code isn't broken .. –  Amr Ayman 14 hours ago

Browse other questions tagged or ask your own question.