使用全名的 Python 程序来打印一个名字的缩写?
我们在这里使用不同的 python 内置函数。首先,我们使用 split()。将单词拆分为一个列表。然后遍历倒数第二个单词,使用 upper() 函数打印首字母大写,然后添加最后一个单词作为名字的标题,此处我们使用 title(),title 函数将第一个字母转换为大写字母。
例
Input Pradip Chandra Sarkar Output P.C Sarkar
算法
fullname(str1) /* str1 is a string */ Step 1: first we split the string into a list. Step 2: newspace is initialized by a space(“”) Step 3: then traverse the list till the second last word. Step 4: then adds the capital first character using the upper function. Step 5: then get the last item of the list.
代码示例
# python program to print initials of a name
def fullname(str1):
# split the string into a list
lst = str1.split()
newspace = ""
# traverse in the list
for i in range(len(lst)-1):
str1 = lst[i]
# adds the capital first character
newspace += (str1[0].upper()+'.')
# l[-1] gives last item of list l.
newspace += lst[-1].title()
return newspace
# Driver code
str1=input("Enter Full Name ::>")
print("Short Form of Name Is ::>",fullname(str1))
输出
Enter Full Name ::>pradip chandra sarkar Short Form of Name Is ::> P.C.Sarkar
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP