简体   繁体   English

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

[英]How to print a space between each letter of a word in a list on a new line?

What I want 我想要的是

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
>>>

What I tried 我尝试了什么

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.

相关问题 如何打印单词,但在每行之后都添加一个字母 - how to print a word but after every new line it adds a letter to it 如何打印2D列表,以便每个列表都在换行符上带有空格,没有任何“”或[] - How to print a 2D list so that each list is on a new line with a space, without any “” or [] 如何输出每个字母之间带有空格的字符串 - How to output a string with a space between each letter 循环打印两个列表,以获得两列在每个列表的每个元素的第一个字母之间具有固定(自定义集)空间 - Loop print through two lists to get two columns with fixed(custom set) space between the first letter of each element of each list 如何在嵌套列表的新行上打印列表的每个元素 - How to print each element of a list on a new line in a nested list 如何获取单词列表的每个字母 python - How to get each letter of word list python 将每行的第一个单词/字母写入新文件 - Write the first word/letter of each line to a new file 如何打印列表中每个元素的第一个字母 - how to print first letter of each element in list 如何使用 pysimplegui 在新行中打印列表的每个元素? - How do I print each element of list in a new line with pysimplegui? 如何在一行中的列表中打印每个字符串的首字母? - How do I print the first letter of each string in a list in one line?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM