s = 'the brown fox'

...在这里做点什么……

S应为:

'The Brown Fox'

最简单的方法是什么?


当前回答

另一个解决方案是:

" ".join(map(lambda d: d.capitalize(), word.split(' ')))

其他回答

在Python中,您可以使用title()方法将字符串中的每个单词大写:

string = "this is a test string"
capitalized_string = string.title()
print(capitalized_string)

输出:

This Is A Test String

不要忽视空白的保留。如果你想处理“fred flinstone”,你得到的是“fred flinstone”而不是“fred flinstone”,你已经破坏了你的空白空间。上面的一些解决方案会丢失空白。这里有一个解决方案,适用于Python 2和3,并保留了空白。

def propercase(s):
    return ''.join(map(''.capitalize, re.split(r'(\s+)', s)))

我非常喜欢这个答案:

复制粘贴版本的@jibberia回答:

def capitalize(line):
    return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')])

但是我发送的一些行分离了一些空白的“字符,在尝试执行s[1:]时导致错误。可能有更好的方法,但我必须添加一个if len(s)>0,就像在

return ' '.join([s[0].upper() + s[1:] for s in line.split(' ') if len(s)>0])

另一个解决方案是:

" ".join(map(lambda d: d.capitalize(), word.split(' ')))

你可以试试这个。简单而利落。

def cap_each(string):
    list_of_words = string.split(" ")

    for word in list_of_words:
        list_of_words[list_of_words.index(word)] = word.capitalize()

    return " ".join(list_of_words)