【问题标题】:Add an enter to string every 22 characters, waiting until a space [duplicate]每 22 个字符向字符串添加一个输入,等到一个空格 [重复]
【发布时间】:2019-11-09 19:50:57
【问题描述】:

我试图让我的代码每 22 个字符插入一个 \n 到我的代码中,但如果第 22 个字符不是空格,它会等到有一个空格时再插入 \n

过去一小时我曾尝试在 StackOverflow 上查找一些代码,但大多数似乎都因一些更改而中断,因为它们是专门针对该问题而设计的。

这是我尝试过的一些代码

count = 0
s = "I learned to recognise the through and primitive duality of man; I saw that, of the two natures that contended in the field of my consciousness, even if I could rightly be said to be either, it was only because I was radically both"
newS = ""
enterASAP = False
while True:
    count += 1
    if enterASAP == True and s[count-1] == " ":
        newS = (s[:count] + "\n" + s[count:])
    if count % 22 == 0:
        if s[count-1] == " ":
            newS = (s[:count] + "\n" + s[count:])
        else:
            enterASAP = True
    if count == len(s):
        print(newS)
        print("Done")
        break

我希望它产生类似
I learned to recognise the thorough and primitive
.......
请注意,它会等待空格,然后计数会从 the 重置为 primitive,而不是添加代码等待空格的 5 个额外字母。

我的代码产生了它开头的确切字符串。这让我感到困惑

【问题讨论】:

  • 我建议看一下内置模块textwrap
  • if enterASAP == True and s[count-1] == " ": newS = (s[:count] + "\n" + s[count:])之后将enterASAP设置为False
  • 哇,textwrap 模块完全符合我的要求,非常感谢 Andrej,如果您或其他人可以将其放入答案中,我将接受并关闭它
  • 每次分配 newS = (s[:count] + "\n" + s[count:]) ,它都会覆盖前一个。所以最后当你打印 newS 时,你只会得到一个换行符

标签: python enter


【解决方案1】:

如 cmets 中所述,带有textwrap (doc) 的版本:

import textwrap

s = "I learned to recognise the through and primitive duality of man; I saw that, of the two natures that contended in the field of my consciousness, even if I could rightly be said to be either, it was only because I was radically both"

print('\n'.join(textwrap.wrap(s, 22)))

打印:

I learned to recognise
the through and
primitive duality of
man; I saw that, of
the two natures that
contended in the field
of my consciousness,
even if I could
rightly be said to be
either, it was only
because I was
radically both

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 2013-12-13
    • 2017-07-14
    • 2012-08-28
    • 1970-01-01
    • 2020-08-23
    • 2020-04-13
    相关资源
    最近更新 更多