【问题标题】:How to print a space between each letter of a word in a list on a new line?如何在新行的列表中打印单词的每个字母之间的空格?
【发布时间】:2018-11-03 23:17:51
【问题描述】:

我想要什么

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)

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

【问题讨论】:

    标签: python list for-loop


    【解决方案1】:

    你可以使用str.join()

    sentence = ["This","is","a","short","sentence"]
    
    for w in sentence:
        print(' '.join(w))
    

    【讨论】:

    • 谢谢,str.join() 在这种情况下似乎很方便
    【解决方案2】:

    您可以使用字符串是序列的事实,可以使用 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,SpghttCd 的代码使用了 1.33 毫秒,而我的使用了 5.18 毫秒。所以我的代码在代码中略短,但在执行时明显更长。我怀疑 Python 使用时间来计算如何在我的代码中打印每个项目,而在 SpghttCd 的代码中只打印一个项目。该项目的准备时间更长,但打印速度更快——显然,速度要快得多。 “在幕后”,打印每个项目的设置必须很大,类似于 Python 处理列表的方式比 numpy 的数组慢。
    猜你喜欢
    • 1970-01-01
    • 2015-04-17
    • 2019-10-31
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多