每隔22个字符在字符串中添加一个enter键,等到空格

时间:2019-06-27 18:39:46

标签: python enter

我正在尝试让我的代码每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个额外字母。

我拥有的代码会产生确切的字符串。哪个让我感到困惑

1 个答案:

答案 0 :(得分:0)

如评论中所述,带有textwrapdoc)的版本:

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