使用全名的 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

更新時間:2019-07-30

5 千+ 瀏覽量

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.