如何通过在空格处拆分字符串,获取索引为0的字符并将其连接在一起,并大写该字符来创建一个首字母缩写?

3

我的代码

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

second = beginning.upper()

third = second.split()

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

print(fourth)

我似乎找不到我的问题所在。这段代码的目的是将用户输入的短语全部转换成大写字母,将其分割成单词,将每个单词的第一个字符连接起来,并打印出来。我觉得应该有一个循环语句,但我不确定它是否正确或应该放在哪里。

6个回答

4

假设输入为“Federal Bureau of Agencies”

键入third [0]会给出拆分的第一个元素,即“Federal”。您想要在拆分的每个元素中获取第一个元素。使用生成器推导式或列表推导式将 [0] 应用于列表中的每个项:

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

在Python中,使用显式循环并不符合惯用语法。生成器推导式更短、更易读,并且不需要使用显式累加器变量。

2
当你运行代码third[0]时,Python将索引变量third并给出它的第一个部分。 .split()的结果是字符串列表。 因此,third[0]是单个字符串,即第一个单词(全部大写)。
你需要某种循环来获取每个单词的第一个字母,否则你可以使用正则表达式处理一些东西。 我建议使用循环。
试试这个:
fourth = "".join(word[0] for word in third)

在调用.join()时,有一个小的for循环。Python将其称为“生成器表达式”。变量word会依次设置为来自third的每个单词,然后word[0]可以得到您想要的字符。


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'
>>> 

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() 

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

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接