s = 'the brown fox'

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

S应为:

'The Brown Fox'

最简单的方法是什么?


当前回答

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

其他回答

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

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

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

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

输出:

This Is A Test String

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

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

只大写第一个字母。

大写的单词…

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

一个快速函数适用于python3

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> capitalizeFirtChar = lambda s: s[:1].upper() + s[1:]
>>> print(capitalizeFirtChar('помните своих Предковъ. Сражайся за Правду и Справедливость!'))
Помните своих Предковъ. Сражайся за Правду и Справедливость!
>>> print(capitalizeFirtChar('хай живе вільна Україна! Хай живе Любовь поміж нас.'))
Хай живе вільна Україна! Хай живе Любовь поміж нас.
>>> print(capitalizeFirtChar('faith and Labour make Dreams come true.'))
Faith and Labour make Dreams come true.