【问题标题】:Function That Returns Capitalized Initials of Name返回名称首字母大写的函数
【发布时间】: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


    【解决方案1】:

    这是我的回答:

    1. 将字符串拆分为列表
    2. 使用rangei 遍历元素
    3. 在迭代期间为每个元素获取索引 0(因此 words[i][0]
    4. 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
    

    【讨论】:

      【解决方案2】:
      def initials(name):
          words = name.split()
          result = "" 
          for word in words:
              result += word[0].upper()
          return result
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          【解决方案4】:

          这应该可以工作

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

          【讨论】:

            【解决方案5】:

            您可以使用list comprehension

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

            edit:应该多解释一下 列表推导允许您在迭代时构建列表。 所以首先我们通过用空格fullname.split(' ') 分割全名来构建一个列表。当我们得到这些值时,我们取第一个字母 x[0] 并将其大写 .upper()。最后我们将列表合并为一个没有空格的''.join(...)

            这是一个不错的单行,速度非常快,当您继续使用 python 时会以各种形式弹出。

            【讨论】:

            • 感谢您的解释 - 有道理。很高兴知道。
            • 如果全名包含 2 个连续的空格,则会失败。我已经成功使用了这个:''.join([x[0].upper() for x in filter(None, fullname.split(' '))])
            【解决方案6】:

            怎么样:

            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
            

            【讨论】:

            • 谢谢,我没想到要这样附加首字母。你能解释一下为什么“for name in name_list:”会贯穿每个名字而不是每个字母吗?
            • 这是因为xs.split() 函数将返回list 而不是字符串,因此name_list 等于["John", "Smith"]。因此for name in name_list 语句逐个遍历列表项,而不是字符串中的每个字母
            猜你喜欢
            • 2016-08-21
            • 1970-01-01
            • 1970-01-01
            • 2016-12-23
            • 2019-07-01
            • 2019-11-21
            • 2022-06-30
            • 2016-04-21
            • 2013-09-02
            相关资源
            最近更新 更多