gpt4 book ai didi

python - 垂直打印字符串 - Python3.2

转载 作者:太空宇宙 更新时间:2023-11-03 13:01:26 25 4
gpt4 key购买 nike

我正在编写一个脚本,它将作为用户输入的字符串,并垂直打印它,如下所示:

input = "John walked to the store"

output = J w t t s
o a o h t
h l e o
n k r
e e
d

大部分代码我都写好了,如下:

import sys

def verticalPrint(astring):
wordList = astring.split(" ")
wordAmount = len(wordList)

maxLen = 0
for i in range (wordAmount):
length = len(wordList[i])
if length >= maxLen:
maxLen = length

### makes all words the same length to avoid range errors ###
for i in range (wordAmount):
if len(wordList[i]) < maxLen:
wordList[i] = wordList[i] + (" ")*(maxLen-len(wordList[i]))

for i in range (wordAmount):
for j in range (maxLen):
print(wordList[i][j])

def main():
astring = input("Enter a string:" + '\n')

verticalPrint(astring)

main()

我无法弄清楚如何使输出正确。我知道它是 for 循环的问题。它的输出是:

input = "John walked"

output = J
o
h
n

w
a
l
k
e
d

有什么建议吗? (此外,我希望只使用一次 print 命令。)

最佳答案

使用itertools.zip_longest:

>>> from itertools import zip_longest
>>> text = "John walked to the store"
for x in zip_longest(*text.split(), fillvalue=' '):
print (' '.join(x))
...
J w t t s
o a o h t
h l e o
n k r
e e
d

关于python - 垂直打印字符串 - Python3.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19622169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com