水平打印分开的单词字符串
我刚开始学习Python,感觉这真的让我很困惑,因为我想用字符串来练习测试。
输出结果应该像上面那样。两个列之间的间隔是一个制表符。
3 个回答
0
这里有一种基本的方法,不需要使用其他模块。
strings=["groceries","restaurant","hotel"]
# detect longest string
string_max=0
for s in strings:
if len(s)>string_max: string_max=len(s)
# print the strings
for i in range(string_max):
# put the i-th character of each string in a list
c=[]
for s in strings:
try:
c.append(s[i])
except: # is the string is too short, an index error will be thrown
c.append(" ")
# print the list of characters per each line
print ("\t".join(c))
输出结果:
g r h
r e o
o s t
c t e
e a l
r u
i r
e a
s n
t
当然,这个方法还可以通过比如列表推导式来进一步优化,但作为一个基本的方法,这个已经可以用了。
2
你可以使用 itertools.zip_longest
来完成这个任务:
from itertools import zip_longest
def print_words(words):
for t in zip_longest(*words, fillvalue=" "):
print(*t, sep=" ")
words = ["groceries", "restaurant", "hotel"]
print_words(words)
输出结果是:
g r h
r e o
o s t
c t e
e a l
r u
i r
e a
s n
t
1
这里有另一种使用列表推导的方法。
words = ["groceries", "restaurant", "hotel"]
max_length = max(len(word) for word in words)
for i in range(max_length):
output_line = " ".join([word[i] if len(word) > i else " " for word in words])
print(output_line)
输出结果:
g r h
r e o
o s t
c t e
e a l
r u
i r
e a
s n
t