[英]How to print a space between each letter of a word in a list on a new line?
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)
The problem with this is that it prints a space at the beginning and end of every line but I only want a space between each letter 这个问题是它在每行的开头和结尾打印一个空格,但我只想在每个字母之间留一个空格
You could use str.join()
你可以使用
str.join()
sentence = ["This","is","a","short","sentence"]
for w in sentence:
print(' '.join(w))
You could use the facts that a string is a sequence, a sequence can be split into its items with the splat *
operator, and and the print
function prints items by default separated by spaces. 您可以使用字符串是序列的事实,可以使用splat
*
运算符将序列拆分为其项目,并且print
函数默认打印以空格分隔的项目。 Those three facts can be combined into one short line, print(*word)
, if word
is a string. 这三个事实可以组合成一个短行,
print(*word)
,如果word
是一个字符串。 So you can use 所以你可以使用
sentence = ["This","is","a","short","sentence"]
for word in sentence:
print(*word)
This gives the printout 这给出了打印输出
T h i s
i s
a
s h o r t
s e n t e n c e
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.