s = 'the brown fox'

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

S应为:

'The Brown Fox'

最简单的方法是什么?


当前回答

使用非均匀空格将字符串大写

我想补充一下@Amit Gupta关于非均匀空间的观点:

从最初的问题中,我们想要大写字符串s = 'the brown fox'中的每个单词。如果字符串s = 'the brown fox'有不均匀的空格。

def solve(s):
    # If you want to maintain the spaces in the string, s = 'the brown      fox'
    # Use s.split(' ') instead of s.split().
    # s.split() returns ['the', 'brown', 'fox']
    # while s.split(' ') returns ['the', 'brown', '', '', '', '', '', 'fox']
    capitalized_word_list = [word.capitalize() for word in s.split(' ')]
    return ' '.join(capitalized_word_list)

其他回答

尽管所有的答案都是令人满意的,但我将尝试涵盖两个额外的情况以及所有前面的情况。

如果空间不均匀,你想保持不变

string = hello    world i  am    here.

如果所有的字符串不是从字母开始

string = 1 w 2 r 3g

在这里你可以使用这个:

def solve(s):
    a = s.split(' ')
    for i in range(len(a)):
        a[i]= a[i].capitalize()
    return ' '.join(a)

这将给你:

output = Hello    World I  Am    Here
output = 1 W 2 R 3g

如果访问[1:],空字符串将引发错误。因此我会使用:

def my_uppercase(title):
    if not title:
       return ''
    return title[0].upper() + title[1:]

只大写第一个字母。

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

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)

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

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

.title()方法不能很好地工作,

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

试试string.capwords()方法,

import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"

来自Python capwords文档:

使用str.split()将参数拆分为单词,使用str.capitalize()将每个单词大写,并使用str.join()连接大写的单词。如果可选的第二个参数sep不存在或为None,则空白字符的运行将被单个空格替换,并且前导和尾部的空白将被删除,否则sep用于分隔和连接单词。