使用Python中的异常将字符串中每个单词的首字母大写

时间:2016-06-28 01:43:48

标签: python

这就是我所得到的:

def cap(s):    
    lst = s.split()   
    res = ''     
    for word in lst:
        res = res + ' '+ word.capitalize()
    return res

我如何修改它以大写每个单词中的每个字母,除了"和","等单词是","它","如果"等?

1 个答案:

答案 0 :(得分:3)

只过滤掉不应大写的字词:

no_caps_list = ["and", "is", "it", "if"]
def cap(s):    
    lst = s.split()   
    res = ''     
    for word in lst:
        if word not in no_caps_list:
            word = word.capitalize()
        res = res + ' '+ word
    return res

该函数的清洁版可以写成:

def sensible_title_caps(str, no_caps_list = ["and", "is", "it", "if"]):
    words = []  
    for word in str.split():
        if word not in no_caps_list:
            word = word.capitalize()
        words.append(word)
    return " ".join(words)

在这里,我们删除不需要的临时变量,并接受一个单词列表,以便不作为具有合理默认值的参数(no_caps_list)进行大写。

或者像列表理解那样可怕的混淆:

def obfuscated_caps(str, no_caps_list = ["and", "is", "it", "if"]):
    return " ".join([w in no_caps_list and w or w.title() for w in str.split()])