【问题标题】:How can I print the first letter of each word of a string? [duplicate]如何打印字符串中每个单词的第一个字母? [复制]
【发布时间】:2021-06-21 17:04:20
【问题描述】:

我是 Python 新手,我想更多地尝试字符串操作。

我想打印语句中每个单词的首字母...

'I like sweet and savoury food'

...所以输出看起来像这样:

'I l s a s f'

【问题讨论】:

标签: python string printing output


【解决方案1】:

一个简单的“pythonic”方法是

print(' '.join(word[0] for word in sentence.split()))

拥有像这样的for 循环称为列表推导。你可以详细写出来:

split = sentence.split()
result = ''
for word in split:
    result += word[0] + ' '
print(result.strip()) # strip to get rid of trailing space    

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
  • 2022-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 1970-01-01
相关资源
最近更新 更多