s = 'the brown fox'

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

S应为:

'The Brown Fox'

最简单的方法是什么?


当前回答

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

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

输出:

This Is A Test String

其他回答

大写的单词…

str = "this is string example....  wow!!!";
print "str.title() : ", str.title();

@Gary02127评论,下面的解决方案适用于带有撇号的标题

import re

def titlecase(s):
    return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(), s)

text = "He's an engineer, isn't he? SnippetBucket.com "
print(titlecase(text))

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

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

对你的问题最简单的解决方法,在我的情况下是有效的:

import string
def solve(s):
    return string.capwords(s,' ') 
    
s=input()
res=solve(s)
print(res)

建议的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'

如果str.title()对您不起作用,请自己大写。

将字符串拆分为单词列表 每个单词的第一个字母大写 把单词连接成一个字符串

一行程序:

>>> ' '.join([s[0].upper() + s[1:] for s in "they're bill's friends from the UK".split(' ')])
"They're Bill's Friends From The UK"

明显的例子:

input = "they're bill's friends from the UK"
words = input.split(' ')
capitalized_words = []
for word in words:
    title_case_word = word[0].upper() + word[1:]
    capitalized_words.append(title_case_word)
output = ' '.join(capitalized_words)