s = 'the brown fox'

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

S应为:

'The Brown Fox'

最简单的方法是什么?


当前回答

建议的str.title()方法并非在所有情况下都有效。 例如:

string = "a b 3c"
string.title()
> "A B 3C"

而不是"A B 3c"

我认为,最好这样做:

def capitalize_words(string):
    words = string.split(" ") # just change the split(" ") method
    return ' '.join([word.capitalize() for word in words])

capitalize_words(string)
>'A B 3c'

其他回答

以防你想裁员

# Assuming you are opening a new file
with open(input_file) as file:
    lines = [x for x in reader(file) if x]

# for loop to parse the file by line
for line in lines:
    name = [x.strip().lower() for x in line if x]
    print(name) # Check the result

建议的str.title()方法并非在所有情况下都有效。 例如:

string = "a b 3c"
string.title()
> "A B 3C"

而不是"A B 3c"

我认为,最好这样做:

def capitalize_words(string):
    words = string.split(" ") # just change the split(" ") method
    return ' '.join([word.capitalize() for word in words])

capitalize_words(string)
>'A B 3c'

当解决方案简单而安全的时候,为什么你要用连接和for循环来使你的生活复杂化?

只要这样做:

string = "the brown fox"
string[0].upper()+string[1:]

正如Mark指出的,你应该使用.title():

"MyAwesomeString".title()

然而,如果你想让Django模板中的第一个字母大写,你可以这样做:

{{ "MyAwesomeString"|title }}

或者使用变量:

{{ myvar|title }}

.title()方法不会在所有测试用例中工作,因此将.capitalize(), .replace()和.split()一起使用是将每个单词的第一个字母大写的最佳选择。

def caps(y):

     k=y.split()
     for i in k:
        y=y.replace(i,i.capitalize())
     return y