每隔22个字符向字符串添加一个enter,直到sp

2024-07-03 07:14:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让我的代码每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个额外字母。你知道吗

我的代码生成了它的起始字符串。这让我很困惑


Tags: andoftheto代码trueifcount
1条回答
网友
1楼 · 发布于 2024-07-03 07:14:30

如注释中所述,带有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

相关问题 更多 >