【发布时间】:2017-04-21 16:51:18
【问题描述】:
我创建了一个 Python 函数,它接受一个参数 fullname,获取 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 中说“如果 fullname 有第二名或第三名或第四名,则返回大写首字母”?还是我走在正确的轨道上?谢谢你。
【问题讨论】:
标签: python list function methods indexing