2017-10-05 203 views
-4

需要與方案援助爲我介紹Python的課程:的Python:需要幫助

編寫一個程序,要求用戶對包含他們的第一個,中間和最後一個名稱的字符串。程序將修改輸入以顯示輸入的首字母。如果一個人輸入「NA」作爲中間名,那麼程序應該只顯示姓和名的首字母縮寫。使用以下字符串測試程序:

Alfred E. Newman A.E.N.約翰·史密斯J.S.

這是我到目前爲止有:

def main(): 

    index = 0 

    #first_name = input("Please enter your first name: ") 
    #middle_name = input("Please enter your middle name: ") 
    #last_name = input("Please enter your last name: ") 

    #first_initial = first_name[0].upper() + "." 
    #middle_initial = middle_name[0].upper() + "." 
    #last_initial = last_name[0].upper() + "." 

    #print("Here are your initials: ", first_initial, middle_initial, last_initial) 

    full_name = input("Please enter your full name (with spaces): ") 
    f_i = "" 
    m_l_i = "" 

    for ch in full_name: 
     if index == 0: 
      f_i = ch.upper() + "." + " " 
     if ch == " ": 
      index += 1 
      m_l_i += full_name[index].upper() + "." + " " 
      index += -1 

     index += 1 

    full = f_i + m_l_i 

    print("Your initials are: ", full) 

main() 

程序工作,但我有添加IF的,如果中間名是「NA」問題

+3

自己做好你的功課。 – mikeb

+0

您可能會發現['split []](https://docs.python.org/2/library/string.html#string.split)輸入字符串更容易。另外,我會避免像'f_i'這樣的變量名。使用更具描述性的內容。 –

回答

0

迭代字符由字符使你的問題更難。您可以使用.split()方法打破字符串,並使用拆包得到名稱

first, middle, last = full_name.split() 

然後,它是非常簡單的

middle_name = "" if middle == "NA" else ... 
0

試試這個。

def get_initials(name): 
    """ Return initials of first, last and middle name. 
    If the middle name is 'NA', return only the initials of the first and the last name. 

    >>> get_initials("Alfred English Newman") 
    >>> 'A.E.N.' 
    >>> get_initials("John NA smith") 
    >>> 'J.S.' 
    """ 

    first, middle, last = name.lower().split() 

    if middle == 'na': 
     initials = first[0] + '.' + last[0] + '.' 
    else: 
     initials = first[0] + '.' + middle[0] + '.' + last[0] + '.' 

    return initials.upper() 


full_name = input("Please enter your full name (with spaces): ") 

print(get_initials(full_name)) 

一對夫婦的試運行:

Please enter your full name (with spaces): John NA smith 
J.S. 

Please enter your full name (with spaces): alfred e newman 
A.E.N. 

Please enter your full name (with spaces): Alfred English Newman 
A.E.N.