2

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?

aschultz
  • 1,658
  • 3
  • 20
  • 30

3 Answers3

3

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.
Sam Craig
  • 875
  • 5
  • 16
  • This is exactly, what I was looking for (more than than plenty hours of frustrating coding :D) Maybe I searched with incongruous keywords. Thank you very much, I appreciate it. – FabianPeters Aug 04 '17 at 17:19
2

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()
TallChuck
  • 1,725
  • 11
  • 28
0

I think you're looking for the textwrap module.

text_wrap.fill(your_text, width=your_width)

leegenes
  • 31
  • 2