【问题标题】:Python: words in a string get stripped in the outputPython:字符串中的单词在输出中被剥离
【发布时间】:2017-08-04 15:34:07
【问题描述】:

我正在用 Python 2.7 编写文本冒险,现在想要制作漂亮的输出。我已经尝试用 Tkinter 制作一个 GUI,但它不起作用,因为用户的文本输入无法在 Tk 中解码,我需要它用于德语变音符号。所以现在我正试图直接在 Python shell 或 Jupyter notebook 中获得良好的输出。问题是,当我执行打印语句时,我得到如下输出:

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.

我厌倦了使用显示的宽度,并认为在 80 个字符后分割字符串会很好,但条件是它只能在空格处分割,而不是在一个单词中分割。我想做这样的事情:

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

字符串是不可变的,所以我想我必须将它转换为一个列表,但是我不知道如何将字符串的拆分位置和列表放在一起。也许是我想得太复杂了。

有没有办法说:如果字符串长度超过 80 个字符,将字符串在最近的空白处拆分到第 80 个字符?

【问题讨论】:

  • 发布实际输入字符串(超过 80 个字符)和预期结果
  • 我认为有这方面的python库。

标签: python string split output newline


【解决方案1】:

使用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.

【讨论】:

  • 这正是我正在寻找的(超过大量令人沮丧的编码时间:D)也许我搜索的关键字不协调。非常感谢,我很感激。
【解决方案2】:

我会查看字符串的前 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()

【讨论】:

  • 这是一种有趣的方法。我也会尝试这种方式。谢谢!
  • 好吧,我在不知道 textwrap 库的情况下写了这篇文章。这可能是一个更好的方法
【解决方案3】:

我认为您正在寻找 textwrap 模块。

text_wrap.fill(your_text, width=your_width)

【讨论】:

  • 这就是我要找的模块。非常感谢您的回答,我很感激。
猜你喜欢
  • 2018-09-28
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 2018-03-16
  • 2016-11-04
  • 1970-01-01
  • 2021-08-12
  • 2018-04-20
相关资源
最近更新 更多