代码之家  ›  专栏  ›  技术社区  ›  twhale

如何避免大写的缩写词和缩写词被.capital()小写?蟒蛇

  •  2
  • twhale  · 技术社区  · 7 年前

    将句子的第一个字母大写 .capitalize() 工作良好。除非句子的第一个单词是类似于“ibm”或“sim”的首字母缩略词,并且是小写的(第一个字母除外)。例如:

    L = ["IBM", "announced", "the", "acquisition."]
    L = [L[0].capitalize()] + L[1:]
    L = " ".join(L)
    print(L)
    

    给予:

    "Ibm announced the acquisition."
    

    但我想要这个:

    "IBM announced the acquisition."
    

    有没有办法避免这种情况,例如跳过缩写词,同时仍然输出下面这样的大写句子?

    "IBM's CEO announced the acquisition."
    "The IBM acquisition was announced."
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   iacob    7 年前

    只需将第一个单词的第一个字符大写即可:

    L = ["IBM", "announced", "the", "acquisition."]
    L[0] = L[0][0].upper() + L[0][1:] #Capitalizes first letter of first word
    L = " ".join(L)
    
    print(L)
    >>>'IBM announced the acquisition.'