我創建了一個Python函數,它接受一個參數fullname獲取全名的首字母並將它們大寫打印出來。但是我的代碼存在問題 - 它只能使用兩個名字。如果全名有一箇中間名,即Daniel Day Lewis,則會中斷。返回名稱首字母大寫的函數
這裏是我的嘗試:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
second = name_list[1][0]
return(first.upper() + second.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
顯然,這種嘗試僅包括兩個變量,一個名字和一個第二個名稱。如果我添加第三個變量,就像這樣:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
second = name_list[1][0]
third = name_list[2][0]
return(first.upper() + second.upper() + third.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
我得到:
IndexError: list index out of range on line 10
(也就是行)
third = name_list[2][0]
當然,如果我改變全稱此功能無法正常工作到「Ozzie Smith Jr」。但是我的功能必須工作,無論名稱中是否有1個,2個,3個或4個名稱。我要這樣說:
def get_initials(fullname):
xs = (fullname)
name_list = xs.split()
print(name_list)
#Given a person's name, return the person's initials (uppercase)
first = name_list[0][0]
#if fullname has a second name:
second = name_list[1][0]
#if fullname has a third name:
third = name_list[2][0]
#if fullname has one name:
return(first.upper())
#if fullname has two names:
return(first.upper() + second.upper())
#if fullname has three names:
return(first.upper() + second.upper() + third.upper())
#if fullname has three names:
return(first.upper() + second.upper() + third.upper + fourth.upper())
answer = get_initials("Ozzie Smith")
print("The initials of 'Ozzie Smith' are", answer)
我怎麼說在Python「如果全名有第二個名字或第三名或第四名,返回大寫字母」?還是我在正確的軌道上?謝謝。
感謝縮寫,我沒有想想追加這樣的首字母縮寫。你能解釋爲什麼「name_list中的姓名:」通過每個姓名而不是每個字母? – Sean
這是因爲'xs.split()'函數會返回一個'list'而不是一個字符串,所以'name_list'等於'[「John」,「Smith」]'。因此,name_list中的'name'語句逐個遍歷列表項,而不是字符串中的每個字母 – Mike
我看到了 - 謝謝! – Sean