Python:需要帮助

时间:2017-10-05 13:56:54

标签: python

需要协助我的Python课程简介:

编写一个程序,要求用户输入包含其名字,中间名和姓氏的字符串。程序将修改输入以显示输入的首字母。如果一个人输入“NA”作为中间名,那么程序应该只显示名字和姓氏的首字母。使用以下字符串测试程序:

Alfred E. Newman A.E.N. John NA Smith 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()

该程序有效,但如果中间名是" NA"

,我在添加IF方面遇到问题

2 个答案:

答案 0 :(得分:0)

逐个字符迭代会让你的问题变得更难。您可以使用.split()方法中断字符串,并使用解压缩来获取名称

first, middle, last = full_name.split()

然后它很简单

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

答案 1 :(得分: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.