我创建了一个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",这个功能确实有用。但是无论fullname中是否有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)
如何说"如果fullname有第二个名字或第三个名字或第四个名字,则返回大写字母"在Python?还是我走在正确的轨道上?谢谢。
答案 0 :(得分:5)
您可以使用list comprehension:
s = ''.join([x[0].upper() for x in fullname.split(' ')])
编辑:应该解释一下
list comprehensions允许您在迭代时构建列表。
首先,我们通过将fullname与空格fullname.split(' ')
分开来构建列表。当我们得到这些值时,我们采用第一个字母x[0]
并将其大写为.upper()
。最后,我们将列表加入到没有空格''.join(...)
的列表中。
这是一个非常好的单线程,非常快,并且会在您继续使用python时以各种形式弹出。
答案 1 :(得分:3)
如下:
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
答案 2 :(得分:2)
这应该有效
map(str.upper, zip(*the_persons_name.split())[0])
答案 3 :(得分:2)
如下所示的一个班轮的另一个方差,我们可以加入所有的首字母1然后最后进行upper
1次拍摄
''.join(i[0] for i in a.split()).upper()
答案 4 :(得分:2)
这是我的答案:
range
和i
遍历元素words[i][0]
)words[i][0].upper
表示问题的大写要求def initials(phrase):
words = phrase.split()
result = ""
for i in range(len(words)):
result += words[i][0].upper()
return result
print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS
答案 5 :(得分:1)
def initials(name):
words = name.split()
result = ""
for word in words:
result += word[0].upper()
return result