[英]How do I turn this string into a list, and then make it have a max line length in python 3.3?
因此,我有一個很大的腳本,已將其定義為文本。 我試圖將它們變成一個列表,然后當用戶輸入數字時,這將是該行的最大長度,並將所有字符都放在該最大長度之后的下一行。
def main():
lmax = input("What would you like the maximum line length to be?")
text='''Mother: Hi, honey.
Grandson: Hi, Mom.
Mother: You feeling any better?
Grandson: A little bit.
Mother: Guess what?
Grandson: What?
Mother: Your Grandfather's here.
Grandson: Mom, can't you tell him I'm sick?
Mother: You're sick? That's why he's here.
Grandson: He'll pinch my cheek. I hate that.
Mother: Maybe he won't.
Grandfather: Heyyyy!! How's the sickie? Heh?
Mother: I think I'll leave you two pals alone.
Grandfather: I brought you a special present.
Grandson: What is it?
Grandfather: Open it up.
Grandson: A book?
Grandfather: That's right. When I was your age, television was called books. And this is a special book. It was the book my father used to read to me when I was sick, and I used to read it to your father. And today I'm gonna read it to you.
Grandson: Has it got any sports in it?
Grandfather: Are you kidding? Fencing, fighting, torture, revenge, giants, monsters, chases, escapes, true love, miracles...
Grandson: Doesn't sound too bad. I'll try to stay awake.
Grandfather: Oh, well, thank you very much, very nice of you. Your vote of confidence is overwhelming. All right. The Princess Bride, by S. Morgenstern. Chapter One. Buttercup was raised on a small farm in the country of Florin.'''
lines = text.split('\n')
count = 0
for line in lines:
count += 1
text = line.split()
out = ' '.join(text)
if str(len(out))>lmax:
newout=line.split('\n')
print(str(count).rjust(3)+'/'+newout+'/'+str(len(newout)))
print(str(count).rjust(3)+'/'+newout+'/'+str(lmax - len(newout)))
elif str(len(out))<lmax:
print(str(count).rjust(3)+'/'+out+'/'+str(len(out)))
我相信我在正確的道路上,但我不確定100%。 任何幫助表示贊賞。
您可以按照以下方式進行
import textwrap
n = input("Max length: ")
# for line in text.split("\n"):
for line in text.splitlines():
print(textwrap.fill(textwrap.dedent(line), n))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.