每 22 个字符添加一个 enter to string,等待 space
Add an enter to string every 22 characters, waiting until a space
我试图让我的代码每 22 个字符插入一个 \n
到我的代码中,但是如果第 22 个字符不是 space 它会等到有一个然后插入 \n
那里。
我曾尝试在 Whosebug 上查找过去一个小时的一些代码,但大多数似乎都因一些更改而中断,因为它们是专门针对该问题而设计的。
这是我试过的一些代码
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
.......
请注意,它等待 space,然后计数从 the
重置为 primitive
,而不是添加代码等待 [=] 的 5 个额外字母30=].
我的代码生成了它开头的确切字符串。这让我感到困惑
正如评论中所讨论的那样,带有 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
我试图让我的代码每 22 个字符插入一个 \n
到我的代码中,但是如果第 22 个字符不是 space 它会等到有一个然后插入 \n
那里。
我曾尝试在 Whosebug 上查找过去一个小时的一些代码,但大多数似乎都因一些更改而中断,因为它们是专门针对该问题而设计的。
这是我试过的一些代码
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
.......
请注意,它等待 space,然后计数从 the
重置为 primitive
,而不是添加代码等待 [=] 的 5 个额外字母30=].
我的代码生成了它开头的确切字符串。这让我感到困惑
正如评论中所讨论的那样,带有 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