python - 从字符串创建首字母缩写词的函数
问题描述
我从学校得到了一个作业,我必须创建一个函数,该函数接收一个字符串并将字符串中每个单词的首字母的连接作为首字母缩略词返回。返回应该看起来像" 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 ')
到目前为止,这只是为了计算单词在给定文本中的位置。我不知道如何连接属于该位置的单词,以便我可以继续然后创建首字母缩略词。
解决方案
这里 :
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))
推荐阅读
- php - PHP/SQL 分组
- regex - 正则表达式匹配字符串并忽略区分大小写
- google-classroom - 仅限 Google Classroom API 访问
- wordpress - 如何限制商店经理编辑订单价格
- openssl - Openshift:创建直通安全路由
- spring - 在 Spring Boot Hibernate 中覆盖默认表模式
- c# - 为 SQL 连接字符串模拟用户 c# MVC
- arrays - 使用 $exists 的 MongoDB 查询和数组
- jupyter-notebook - 如何在不执行单元格的情况下加载 jupyter-notebook
- machine-learning - 机器学习中的差异结果