Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在新行上打印列表中单词的每个字母之间的空格? 我想要什么 我试过的_Python_List_For Loop - Fatal编程技术网

Python 如何在新行上打印列表中单词的每个字母之间的空格? 我想要什么 我试过的

Python 如何在新行上打印列表中单词的每个字母之间的空格? 我想要什么 我试过的,python,list,for-loop,Python,List,For Loop,问题是它在每行的开头和结尾都打印一个空格,但我只希望每个字母之间有一个空格您可以使用str.join() 您可以使用以下事实:字符串是一个序列,序列可以使用splat*运算符拆分为其项,并且print函数默认情况下打印由空格分隔的项。如果word是一个字符串,那么这三个事实可以组合成一个短行,print(*word)。所以你可以用 sentence = ["This","is","a","short","sentence"] for word in sentence: print(*w

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

您可以使用
str.join()


您可以使用以下事实:字符串是一个序列,序列可以使用splat
*
运算符拆分为其项,并且
print
函数默认情况下打印由空格分隔的项。如果
word
是一个字符串,那么这三个事实可以组合成一个短行,
print(*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

谢谢,
str.join()?在iPython中使用
%timeit
,spighttcd的代码使用了1.33毫秒,而我的代码使用了5.18毫秒。因此,我的代码在代码上略短,但在执行上明显更长。我怀疑Python会用时间来计算如何打印代码中的每一项,而在SpghttCd的代码中只打印一项。这个项目需要更长的准备时间,但打印速度更快——显然,要快得多。“在引擎盖下”,打印每个项目的设置必须很大,类似于Python处理列表列表的速度比numpy的数组慢。
sentence = ["This","is","a","short","sentence"]

for w in sentence:
    print(' '.join(w))
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