3

我的代码

beginning = input("What would you like to acronymize? : ")

second = beginning.upper()

third = second.split()

fourth = "".join(third[0])

print(fourth)

我似乎无法弄清楚我错过了什么。该代码应该是用户输入的短语,将其全部大写,将其拆分为单词,将每个单词的第一个字符连接在一起,然后打印出来。我觉得某处应该有一个循环,但我不完全确定这是否正确或放在哪里。

4

6 回答 6

4

说输入是“联邦机构局”

键入third[0]为您提供了拆分的第一个元素,即“联邦”。你想要精灵中每个元素的第一个元素。使用生成器推导或列表推导应用于列表[0]中的每个项目:

val = input("What would you like to acronymize? ")
print("".join(word[0] for word in val.upper().split()))

在 Python 中,在这里使用显式循环是不习惯的。生成器推导更短且更易于阅读,并且不需要使用显式的累加器变量。

于 2014-05-19T21:49:57.983 回答
2

当您运行代码third[0]时,Python 将为变量编制索引third并为您提供它的第一部分。

的结果.split()是一个字符串列表。因此,third[0]是单个字符串,第一个单词(全部大写)。

你需要某种循环来获取每个单词的第一个字母,否则你可以用正则表达式做一些事情。我建议循环。

尝试这个:

fourth = "".join(word[0] for word in third)

for调用内部有一个小循环.join()。Python 将其称为“生成器表达式”。该变量wordthird依次设置为 from 中的每个单词,然后word[0]为您获取所需的字符。

于 2014-05-19T21:51:11.270 回答
1

这样对我有用:

>>> a = "What would you like to acronymize?"
>>> a.split()
['What', 'would', 'you', 'like', 'to', 'acronymize?']
>>> ''.join([i[0] for i in a.split()]).upper()
'WWYLTA'
>>> 
于 2014-05-19T21:49:53.443 回答
0

一种直观的方法是:

  1. 使用输入(或 python 2 中的 raw_input)获取句子
  2. 将句子拆分为单词列表
  3. 获取每个单词的第一个字母
  4. 用空格字符串连接字母

这是代码:

sentence = raw_input('What would you like to acronymize?: ')
words = sentence.split() #split the sentece into words
just_first_letters = [] #a list containing just the first letter of each word

#traverse the list of words, adding the first letter of
#each word into just_first_letters
for word in words:
    just_first_letters.append(word[0])
result = " ".join(just_first_letters) #join the list of first letters
print result
于 2014-05-19T22:00:47.030 回答
0
name = input("Enter uppercase with lowercase name")

print(f'the original string = ' + name)

def uppercase(name):
    res = [char for char in name if char.isupper()]
    print("The uppercase characters in string are : " + "".join(res))

uppercase(name)
于 2022-03-03T11:30:21.903 回答
0
#acronym2.py
#illustrating how to design an acronymn
import string
def main():
    sent=raw_input("Enter the sentence: ")#take input sentence with spaces 
    
    for i in string.split(string.capwords(sent)):#split the string so each word 
                                                 #becomes 
                                                 #a string
        print string.join(i[0]),                 #loop through the split 
                                                 #string(s) and
                                                 #concatenate the first letter 
                                                 #of each of the
                                                 #split string to get your 
                                                 #acronym
    
        
    
main() 
于 2017-07-05T09:17:23.417 回答