2017-08-04 94 views
1

我在Python 2.7中编写了一个文本冒险,现在想要输出一个漂亮的输出。我已经试着用Tkinter制作一个GUI,但它不起作用,因为用户的文本输入无法在Tk中解码,我需要它用于德语变音。所以现在我试图在python外壳或者jupyter笔记本上直接获得好的输出。问题是,那个时候我做了打印语句,我得到一个输出,如:Python:字符串中的单词在输出中被去除

这是一个文本和一点点EXA

mple显示的问题。


但是我当然不想让单词被剥离,就像'example'一样。它应该是这样的:

这是一个文本和一点点

例子来说明这个问题。


我厌倦了显示器的宽工作和思考的,这将是很好的后80个字符的字符串分割,但与条件,它应该只在空白被分裂,而不是在一个字。我想要做这样的事情:

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

字符串是不变的,所以我想我有隐蔽它在列表中,但我不知道如何把字符串和的分割位置一起列出。也许我觉得太复杂了。

有没有办法说:如果字符串长度超过80个字符,请将字符串以最近的空格分隔为第80个字符。

+0

后实际输入的字符串(超过80个字符)和预期结果 – RomanPerekhrest

+0

我想有Python库这一点。 – quamrana

回答

2

使用textwrap module

例如,如果你想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. 
+0

这正是我正在寻找的东西(比令人沮丧的编码长达数小时:D)也许我用不一致的关键字进行搜索。非常感谢,我很感激。 – FabianPeters

0

我认为你正在寻找的textwrap模块。

text_wrap.fill(your_text, width=your_width)

+0

这是模块,我在找什么。非常感谢您的回答,我很感激。 – FabianPeters

1

我想看看前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() 
+0

这是一个有趣的方式来做到这一点。我也会尝试这种方式。谢谢! – FabianPeters

+0

我写这篇文章时并不知道'textwrap'库。这可能是更好的方法 – TallChuck

相关问题