Python 从句子字符串中提取每个单词的第一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41191424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:32:49  来源:igfitidea点击:

Extract first character of each word from the sentence string

pythonstring

提问by djthegamer1133

I need to make a code that when you enter a text it takes the first letter from each word in the sentence you placed.

我需要编写一个代码,当您输入文本时,它会从您放置的句子中的每个单词中取第一个字母。

For example, for sample string "I like to play guitar and piano and drums", it should print "Iltpgapad"

例如,对于示例字符串"I like to play guitar and piano and drums",它应该打印"Iltpgapad"

回答by fafl

Try something like this:

尝试这样的事情:

line = "I like to play guitar and piano and drums"
words = line.split()
letters = [word[0] for word in words]
print "".join(letters)

回答by appills

This snippet is compatible with Python 3.x:

此代码段与 Python 3.x 兼容:

print(''.join([x[0] for x in raw_input("Enter text:").split()]))

回答by Mian Asbat Ahmad

line = "I like to play guitar and piano and drums"
letters = ""
words = line.split()
for word in words:
    letters = letters + word[0]
print(" ".join(letters).upper())