简体   繁体   English

返回名称首字母大写的函数

[英]Function That Returns Capitalized Initials of Name

I created a Python function that takes an argument, fullname, gets fullname's initials and prints them out capitalized.我创建了一个 Python 函数,它接受一个参数 fullname,获取 fullname 的首字母并大写打印出来。 But there's a problem with my code - it only works with two names.但是我的代码有问题——它只适用于两个名称。 It breaks if the fullname has a middle name, ie Daniel Day Lewis.如果全名有中间名,即丹尼尔戴刘易斯,它会中断。

Here is what I tried:这是我尝试过的:

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) 

Obviously this attempt only includes two variables, one for the first name and one for the second name.显然,这种尝试只包括两个变量,一个用于第一个名称,一个用于第二个名称。 If I add a third variable, like this:如果我添加第三个变量,如下所示:

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) 

I get:我得到:

IndexError: list index out of range on line 10

(which is the line) (这是线)

third = name_list[2][0]

Of course this function does work if I change fullname to "Ozzie Smith Jr".当然,如果我将全名更改为“Ozzie Smith Jr”,则此功能确实有效。 But my function has to work regardless of whether there are 1, 2, 3, or 4 names in fullname.但是无论全名中是否有 1、2、3 或 4 个名称,我的函数都必须工作。 I need to say something like:我需要这样说:

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)

How do I say "if fullname has a second name or third name or fourth name, return the uppercase initial" in Python?如何在 Python 中说“如果全名有第二个名字或第三个名字或第四个名字,则返回大写首字母”? Or am I on the right track?还是我在正确的轨道上? Thank you.谢谢你。

You can make use of a list comprehension :您可以使用列表理解

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

edit : should probably explain a little more list comprehensions allow you to build a list as you iterate.编辑:应该多解释一点列表推导式允许您在迭代时构建列表。 So first we build a list by splitting fullname with a space fullname.split(' ') .因此,首先我们通过将 fullname 与空格fullname.split(' ')分开来构建一个列表。 As we get those values, we take the fist letter x[0] and uppercase it .upper() .当我们得到这些值时,我们取第一个字母x[0]并将其大写.upper() Finally we join the list into one with no spaces ''.join(...) .最后,我们将列表合并为一个,没有空格''.join(...)

This is a nice one liner that's really fast and will pop up in various forms as you continue working with python.这是一个很好的单行代码,速度非常快,并且会在您继续使用 python 时以各种形式弹出。

How about something like:怎么样:

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

这应该工作

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

一个班轮的另一个变化如下,我们可以把所有的首字母加入第一个然后最后做upper 1个镜头

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

This is my answer:这是我的回答:

  1. Splitting the string into a list将字符串拆分为列表
  2. Iterate through elements using range and i使用rangei遍历元素
  3. Taking index 0 for each element during iteration (Hence words[i][0] )在迭代期间为每个元素取索引 0(因此words[i][0]
  4. words[i][0].upper for the upper case requirement for the question 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
def initials(name):
    words = name.split()
    result = "" 
    for word in words:
        result += word[0].upper()
    return result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 填写首字母 function 中的空白,以便返回收到的短语中包含的单词的首字母,大写 - Fill in the gaps in the initials function so that it returns the initials of the words contained in the phrase received, in upper case 创建一个函数以返回句子中所有大写的单词(不包括逗号) - Creating a function that returns all capitalized words in a sentence (commas excluded) 大写单词功能 - Capitalized Word Function 接受字符串嵌套列表并返回所有字符串大写的新嵌套列表的函数? - Function that takes a nested list of strings and returns a new nested list with all strings capitalized? 单行返回首字母的函数 - Function that return initials in a single line 编写一个显示姓名首字母和姓首字母的表达式 - Writing an expression that displays the first and last initials of a name 如何从DataFrame中的名称中提取首字母 - How to extract initials from name in DataFrame 修复rearrange_name function中使用的正则表达式,使其可以匹配中间名、中间名首字母以及双姓 - Fix the regular expression used in the rearrange_name function so that it can match middle names, middle initials, as well as double surnames 使用x的缩写写函数 - function to write initials using x's Django runserver,导入失败 - 项目名称大写? - Django runserver, import fails - project name capitalized?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM