首页 > 解决方案 > 从字符串创建首字母缩写词的函数

问题描述

我从学校得到了一个作业,我必须创建一个函数,该函数接收一个字符串并将字符串中每个单词的首字母的连接作为首字母缩略词返回。返回应该看起来像" the first letter in word number {counter} is {letter}",其中{counter}是单词在给定字符串中的位置,并且{letter}是单词的第一个字母。最后,我必须连接以下格式" the Acronym for the text given is {acronym}",其中{acronym}是文本的首字母缩写词,它是文本中给出的每个单词的第一个字母的连接。

这是我到目前为止所做的:

def Acronym_Creator(text:str()):

   text= 'Hello World I Need Help'
   if text != '':
       for word in range(len(text.split())):
          Counter=0
          Counter= Counter+word+1
          print (  'The first letter  in  word number {Counter} is ')

到目前为止,这只是为了计算单词在给定文本中的位置。我不知道如何连接属于该位置的单词,以便我可以继续然后创建首字母缩略词。

标签: python

解决方案


这里 :

def acronym(string):
    str_lst = string.split()
    acronym = ""
    for i in str_lst: # go through all the string elements in our list
        acronym += i[0].capitalize() # add the character as 0th position in that string, also you might want to capitalize that letter(if not already). 
    return acronym

String = "Hello World I Need Help"
print(acronym(String))

推荐阅读