s = 'the brown fox'

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

S应为:

'The Brown Fox'

最简单的方法是什么?


当前回答

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

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

其他回答

以防你想裁员

# 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

我非常喜欢这个答案:

复制粘贴版本的@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])

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

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

大写的单词…

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))

.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用于分隔和连接单词。