New*_*101 3 python for-loop list
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
>>>
Run Code Online (Sandbox Code Playgroud)
sentence = [row.replace(""," ") for row in sentence]
for item in sentence:
print(item)
Run Code Online (Sandbox Code Playgroud)
这个问题是它在每行的开头和结尾打印一个空格,但我只想在每个字母之间留一个空格
你可以用 str.join()
sentence = ["This","is","a","short","sentence"]
for w in sentence:
print(' '.join(w))
Run Code Online (Sandbox Code Playgroud)
您可以使用字符串是序列的事实,可以使用splat *运算符将序列拆分为其项目,并且该print函数默认情况下以空格分隔打印项目.这三个事实可以组合成一个短行print(*word),如果word是一个字符串.所以你可以使用
sentence = ["This","is","a","short","sentence"]
for word in sentence:
print(*word)
Run Code Online (Sandbox Code Playgroud)
这给出了打印输出
T h i s
i s
a
s h o r t
s e n t e n c e
Run Code Online (Sandbox Code Playgroud)