【问题标题】:How can capitalize 1st and 4th letter for more than one word in a string? [duplicate]如何将字符串中多个单词的第一个和第四个字母大写? [复制]
【发布时间】:2020-04-29 08:08:59
【问题描述】:

我已经解决了如何将第一个和第四个字母大写的问题,但出于好奇,我试图对列表中的所有单词而不是第一个单词这样做:

def my_function(name):
    if len(name) > 3:
        return name[:3].capitalize() + name[3:].capitalize()
    else:
        return 'Name is too short'

result = my_function('oldmac')
print(result)

【问题讨论】:

    标签: python capitalize


    【解决方案1】:

    您可以对列表中的所有单词应用相同的函数。

    >>> def my_function(name):
    ...     if len(name) > 3:
    ...         return name[:3].capitalize() + name[3:].capitalize()
    ...     else:
    ...         return 'Name is too short'
    
    >>> list_of_words = ['oldmac', 'newmac', 'latestmac']
    >>> capitalized = [my_function(word) for word in list_of_words]
    >>> capitalized
    ['OldMac', 'NewMac', 'LatEstmac']
    

    类似的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-10
      • 2014-11-26
      • 2013-06-11
      • 2015-12-11
      • 1970-01-01
      • 2011-07-20
      • 2011-08-18
      相关资源
      最近更新 更多