简体   繁体   English

输出用户输入的每个单词的第一个字母

[英]Output first letter of each word of user input

I have this code 我有这个代码

#Ask for word
w = input("Type in a word to create acronym with spaces between the words:")

#Seperate the words to create acronym
s = w.split(" ")
letter = s[0]

#print answer 
print(s.upper(letter))

And I know that I need a for loop to loop over the words to get the first letter of each word but I can't figure out how to do it I tried many different types but I kept getting errors. 而且我知道我需要一个for循环遍历单词以获取每个单词的第一个字母,但我无法弄清楚如何做到这一点我尝试了很多不同的类型,但我不断收到错误。

Try this. 尝试这个。 It prints a concatenated version of the first letter of each word. 它打印每个单词的第一个字母的连接版本。

w = input("Type in a word to create acronym with spaces between the words:")
print(''.join([e[0] for e in w.split()]).upper())

Try this 尝试这个

w = input("Type a phrase with a space between the words:")
w_up_split = w.upper().split()
acronym = ""

for i in w_up_split:
    acronym += (i[0])
print(acronym)
for word in w.split(" "):
    first_letter = word[0]
    print(first_letter.upper())

In the code that you gave you are taking the first word in a list of lists. 在您给出的代码中,您将获取列表列表中的第一个单词。

s = w.split(" ")
letter = s[0]

If someone input 'Hi how are you' this s would equal 如果有人输入“你好,你好吗”这个s就等于

s == ["Hi"]["how"]["are"]["you"]

And then letter would equal the first index of s which would be ["Hi"] 然后字母将等于s的第一个索引,即[“Hi”]

You want to go through each word and take each letter 你想通过每个单词并拿走每个字母

acronym = []
for x in s:
    acronym.append(x[0])

Would get what you want. 会得到你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用前一个单词的字母反向替换每个单词的第一个字母 - Reverse-replacing the first letter of each word with the letter of the previous word 如何将 python 中每个单词的首字母大写? - How to capitalize the First letter of each word in python? 短语中每个单词的首字母大写 - Upper case first letter of each word in a phrase 将Python中的每个单词的首字母大写 - Capitalize first letter of each word in the column Python 获取python中每个2个字母的单词的第一个字母 - Get the first letter of each 2-letter word in python 尝试使用功能将用户提示的句子中每个单词的首字母大写 - Trying to capitalize the first letter of each word in a user prompted sentence using a function 如果用户输入字母输出应该是单词 - If user inputs letter output should be word 如果您的用户输入的单词的第一个字母不是大写的,程序将如何终止? - How to do the program will terminate if your user input's first letter of a word is not capitalize? 打印出以字母表中每个字母开头的文件中第一次出现的单词 - Print out the the first occurrence of a word in a file beginning with each letter in the Alphabet 如何获取dataframe列的字符串中每个单词的首字母 - How to get the first letter of each word in a string of dataframe column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM