如何在换行列表中的单词的每个字母之间打印空格?

时间:2018-11-03 23:17:51

标签: python list for-loop

我想要的

sentence = ["This","is","a","short","sentence"]

# Desired Output

T h i s
i s
a
s h o r t
s e n t e n c e
>>>

我尝试过的

sentence = [row.replace(""," ") for row in sentence]

for item in sentence:
    print(item)

问题是它在每行的开头和结尾打印一个空格,但是我只希望每个字母之间都留一个空格

2 个答案:

答案 0 :(得分:7)

您可以使用str.join()

sentence = ["This","is","a","short","sentence"]

for w in sentence:
    print(' '.join(w))

答案 1 :(得分:5)

您可以使用以下事实:字符串是一个序列,可以使用splat *运算符将序列拆分为多个项目,并且print函数默认打印项目,并用空格分隔。如果print(*word)是一个字符串,则可以将这三个事实组合成一条短线word。所以你可以使用

sentence = ["This","is","a","short","sentence"]

for word in sentence:
    print(*word)

这给出了打印输出

T h i s
i s
a
s h o r t
s e n t e n c e