我是 Python 新手,我想尝试更多的字符串操作。
我想打印语句中每个单词的第一个字母...
'I like sweet and savoury food'
... 使输出看起来像这样:
'I l s a s f'
答案 0 :(得分:2)
一个简单的“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