代码之家  ›  专栏  ›  技术社区  ›  Arkistarvh Kltzuonstev

Python:将字符串中除一个单词外的单词的第一个字符大写

  •  0
  • Arkistarvh Kltzuonstev  · 技术社区  · 6 年前

    我有绳子 a = 'thirteen thousand and forty six' . 变量 a 在文字上总是有一定的量。我想大写字符串中每个单词的前几个字符,除了特定的单词 'and' . 以下是我的代码,它正在充分发挥作用:

    b = []
    for i in a.split():
        if i.lower() == 'and':
            b.append(i.lower())
        else:
            b.append(i.capitalize())
    aa = " ".join(b)    #'Thirteen Thousand and Forty Six'
    

    aa = " ".join([k.capitalize() for k in a.split() if k.lower() != 'and'])
    

    但是,它又回来了 'Thirteen Thousand Forty Six' 作为结果字符串,省略单词 “还有”

    问题是,对于这项工作,是否有可能使用列表理解或一些内置函数(不使用regex)的OneLiner?

    3 回复  |  直到 6 年前
        1
  •  4
  •   Selcuk    6 年前

    正确的语法应该是

    aa = " ".join([k.capitalize() if k.lower() != 'and' else k for k in a.split()])
    

    当你把你的 if "and" .

        2
  •  1
  •   aghast    6 年前

    split() )为什么不在“和”上拆分,并使用“和”重新连接?

    aa = " and ".join([word.capitalize() for word in a.split(" and ")])
    
        3
  •  0
  •   Shivam    6 年前

    s = 'thirteen thousand and forty six'
    print(s.title().replace('And', 'and'))
    
        4
  •  -1
  •   Manfre Lörson    6 年前

    你可以在资本化后用和替换“And”

    a = 'thirteen thousand and forty six'
    (' ').join([x.capitalize() for x in a.split(' ')]).replace('And', 'and')