Python - 从单词创建首字母缩略词
给定一个字符串,任务是编写一个Python程序来从该字符串中提取首字母缩略词。
例子:
Input: Computer Science Engineering
Output: CSE
Input: geeks for geeks
Output: GFG
Input: Uttar pradesh
Output: UP
方法一:
需要以下步骤:
- 将输入作为字符串。
- 将字符串的第一个字母添加到输出中。
- 迭代整个字符串并将每个下一个字母添加到空格以输出。
- 将输出更改为大写(必需的首字母缩写词)。
Python3
# function to create acronym
def fxn(stng):
# add first letter
oupt = stng[0]
# iterate over string
for i in range(1, len(stng)):
if stng[i-1] == ' ':
# add letter next to space
oupt += stng[i]
# uppercase oupt
oupt = oupt.upper()
return oupt
# input string
inpt1 = "Computer Science Engineering"
# output acronym
print(fxn(inpt1))
# input string
inpt1 = "geeks for geeks"
# output acronym
print(fxn(inpt1))
# input string
inpt1 = "Uttar pradesh"
# output acronym
print(fxn(inpt1))
Python3
# function to create acronym
def fxn(stng):
# get all words
lst = stng.split()
oupt = ""
# iterate over words
for word in lst:
# get first letter of each word
oupt += word[0]
# uppercase oupt
oupt = oupt.upper()
return oupt
# input string
inpt1 = "Computer Science Engineering"
# output acronym
print(fxn(inpt1))
# input string
inpt1 = "geeks for geeks"
# output acronym
print(fxn(inpt1))
# input string
inpt1 = "Uttar pradesh"
# output acronym
print(fxn(inpt1))
输出:
CSE
GFG
UP
方法二:
需要以下步骤:
- 将输入作为字符串。
- 分词。
- 迭代单词并将第一个字母添加到输出。
- 将输出更改为大写(必需的首字母缩写词)。
蟒蛇3
# function to create acronym
def fxn(stng):
# get all words
lst = stng.split()
oupt = ""
# iterate over words
for word in lst:
# get first letter of each word
oupt += word[0]
# uppercase oupt
oupt = oupt.upper()
return oupt
# input string
inpt1 = "Computer Science Engineering"
# output acronym
print(fxn(inpt1))
# input string
inpt1 = "geeks for geeks"
# output acronym
print(fxn(inpt1))
# input string
inpt1 = "Uttar pradesh"
# output acronym
print(fxn(inpt1))
输出:
CSE
GFG
UP