2016-12-06 33 views
1

我創建了一個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「如果全名有第二個名字或第三名或第四名,返回大寫字母」?還是我在正確的軌道上?謝謝。

回答

2

如何像:

def get_initials(fullname): 
    xs = (fullname) 
    name_list = xs.split() 

    initials = "" 

    for name in name_list: # go through each name 
    initials += name[0].upper() # append the initial 

    return initials 
+0

感謝縮寫,我沒有想想追加這樣的首字母縮寫。你能解釋爲什麼「name_list中的姓名:」通過每個姓名而不是每個字母? – Sean

+1

這是因爲'xs.split()'函數會返回一個'list'而不是一個字符串,所以'name_list'等於'[「John」,「Smith」]'。因此,name_list中的'name'語句逐個遍歷列表項,而不是字符串中的每個字母 – Mike

+0

我看到了 - 謝謝! – Sean

3

您可以使用一個list comprehension的:

s = ''.join([x[0].upper() for x in fullname.split(' ')]) 

編輯:或許應該解釋一下更 列表理解讓你在迭代時建立一個列表。 因此,我們首先通過將姓名與空格fullname.split(' ')分開來構建一個列表。當我們獲得這些數值時,我們會拿拳頭字母x[0]和大寫字母.upper()。最後,我們將列表加入一個沒有空格的列表''.join(...)

這是一個非常好的單線程,它非常快速,並且會在您繼續使用python時以各種形式彈出。

+0

感謝您的解釋 - 有道理。很高興知道。 – Sean

2

這應該工作

map(str.upper, zip(*the_persons_name.split())[0]) 
+2

在一行中有很多很棒的python特性! –

1

如下一個襯墊的其他變化,我們可以加入全部1st然後做upper 1次射門終於

''.join(i[0] for i in a.split()).upper()