FabianPeters
FabianPeters

Reputation: 55

Python: words in a string get stripped in the output

I'm writing a text adventure in Python 2.7 and now want to make nice-looking output. I already tried to make a GUI with Tkinter, but it didn't work, because the user's text input could not be decoded in Tk, and I need it for German Umlauts. So now I'm trying to get good output straight in the Python shell or the Jupyter notebook. The problem is, when I do a print statement, I get output like:

This is a text and just a little exa

mple to show the problem.

But of course I don't want to get words stripped, like 'example'. It should look like this:

This is a text and just a little

example to show the problem.

I tired to work with the width of a display and thought that it would be good to split the string after 80 characters, but with the condition that it should only be split at a whitespace and not in a word. I wanted to do something like this:

def output(string):
    for pos, char in enumerate(string):
        if pos <= 80 and pos >=70 and char == " ":
            templist = string.split(char)
            ...

Strings are immutable, so I think I have to convert it into a list, but then I don't know how to put the split-position of the string and the list together. Maybe I'm thinking too intricately.

Is there a way to say: If the string is longer than 80 characters, split the string at the nearest whitespace to the 80th character?

Upvotes: 2

Views: 236

Answers (3)

TallChuck
TallChuck

Reputation: 1972

I would look at the first 80 characters of a string and find the last occurrence of the space character, and then split your string there. You can use rfind() for this:

string = "This is a text and just a little example to show the problem"
lines = []
while string:
    index = string[:80].rfind(' ')
    if index == -1:
        index = 80
    lines.append(string[:index])
    string = string[index:].lstrip()

Upvotes: 2

leegenes
leegenes

Reputation: 31

I think you're looking for the textwrap module.

text_wrap.fill(your_text, width=your_width)

Upvotes: 0

LVFToENlCx
LVFToENlCx

Reputation: 875

Use the textwrap module.

For example, if you want 40 character line width:

import textwrap
a = '''This is a text and just a little example to show the problem.'''
print("\n".join(textwrap.wrap(a,40)))
##This is a text and just a little example
##to show the problem.

Upvotes: 3

Related Questions