【问题标题】:How to insert space after every element in a list in Python如何在Python列表中的每个元素后插入空格
【发布时间】:2020-01-16 19:40:55
【问题描述】:

我有一个看起来像这样的列表“decrypted_characters”

['mathematician', 'to', 'present', 'a', 'proof', 'of', 'the', 'sensitivity']

我希望它看起来像一个段落,所以我尝试了

decrypted_word = ''.join(decrypted_characters)

当我打印时它看起来像

数学家提出敏感性证明

如何在每个元素后添加空格使其看起来像句子?我希望它看起来像

数学家提出敏感性证明

谢谢!

【问题讨论】:

标签: python-3.x list


【解决方案1】:
decrypted_characters = ['mathematician', 'to', 'present', 'a', 'proof', 'of', 'the', 'sensitivity']
decrypted_word = ' '.join(decrypted_characters)
print(decrypted_word)

试试这个。

【讨论】:

  • 这与现有答案有何不同?
  • @cricket_007 这已经足够接近了,但我只是保持相同的格式,对那个提出问题的人所做的改动最少。
【解决方案2】:

使用join:

In [4]: ' '.join(['mathematician', 'to', 'present', 'a', 'proof', 'of', 'the', 'sensitivity'])

Out[4]: 'mathematician to present a proof of the sensitivity'

【讨论】:

  • 如果列表很长怎么办?
  • 您可以使用展开运算符,decrypted_word = ' '.join([...decrypted_characters]) 这会将您的数组展开,上面的建议应该可以很好地工作
猜你喜欢
  • 2020-07-09
  • 2015-09-11
  • 2021-06-27
  • 2020-03-29
  • 1970-01-01
  • 2022-11-14
  • 2012-09-21
  • 2018-12-08
  • 2017-01-15
相关资源
最近更新 更多