Python:字符串中的单词在输出中被剥离

Python:字符串中的单词在输出中被剥离,python,string,split,output,newline,Python,String,Split,Output,Newline,我正在用Python2.7编写一个文本冒险,现在我想做一个漂亮的输出。我已经尝试过用Tkinter制作GUI,但没有成功,因为用户的文本输入无法在Tk中解码,我需要它用于德语Umlauts。因此,现在我正试图直接在Python shell或Jupyter笔记本中获得良好的输出。问题是,当我执行print语句时,会得到如下输出: This is a text and just a little exa mple to show the problem. 但我当然不想把“例子”这样的词删去。应

我正在用Python2.7编写一个文本冒险,现在我想做一个漂亮的输出。我已经尝试过用Tkinter制作GUI,但没有成功,因为用户的文本输入无法在Tk中解码,我需要它用于德语Umlauts。因此,现在我正试图直接在Python shell或Jupyter笔记本中获得良好的输出。问题是,当我执行print语句时,会得到如下输出:

This is a text and just a little exa

mple to show the problem.

但我当然不想把“例子”这样的词删去。应该是这样的:

This is a text and just a little

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

我厌倦了处理显示器的宽度,并认为最好在80个字符后拆分字符串,但条件是只能在空白处拆分,而不能在一个单词中拆分。我想做这样的事情:

This is a text and just a little

example to show the problem.
def output(string):
    for pos, char in enumerate(string):
        if pos <= 80 and pos >=70 and char == " ":
            templist = string.split(char)
            ...
def输出(字符串):
对于pos,枚举中的字符(字符串):
如果pos=70且char==“”:
templast=string.split(字符)
...
字符串是不可变的,所以我想我必须将它转换成一个列表,但是我不知道如何将字符串和列表的拆分位置放在一起。也许我想得太复杂了

是否有一种说法:如果字符串长度超过80个字符,请在最接近第80个字符的空格处拆分字符串?

使用

例如,如果需要40个字符的线宽:

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.

我想你在找模块


text\u wrap.fill(您的\u text,width=您的\u width)
我会查看字符串的前80个字符,找到最后出现的空格字符,然后在那里拆分字符串。您可以为此使用
rfind()

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()

发布实际输入字符串(超过80个字符)和预期结果我认为有python库可用于此。这正是我所要寻找的(超过许多小时令人沮丧的编码:D)可能是我用不一致的关键字搜索的。非常感谢,非常感谢。这就是我想要的模块。非常感谢你的回答,我很感激。这是一种有趣的方式。我也会这样尝试。非常感谢。我写这篇文章时不知道
textwrap
库。这可能是更好的方式