s = 'the brown fox'

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

S应为:

'The Brown Fox'

最简单的方法是什么?


当前回答

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

只要这样做:

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

其他回答

如果你只想知道第一个字母:

>>> 'hello world'.capitalize()
'Hello world'

但是每个单词都要大写:

>>> 'hello world'.title()
'Hello World'

只是因为这类事情对我来说很有趣,这里还有两个解决方案。

拆分为单词,从拆分的组中为每个单词加首字母大写,然后重新连接。这将把分隔单词的空白改为一个单独的空白,不管它是什么。

s = 'the brown fox'
lst = [word[0].upper() + word[1:] for word in s.split()]
s = " ".join(lst)

编辑:我不记得当我写上面的代码时我在想什么,但是没有必要构建一个显式的列表;我们可以使用生成器表达式以惰性方式来执行此操作。所以这里有一个更好的解决方案:

s = 'the brown fox'
s = ' '.join(word[0].upper() + word[1:] for word in s.split())

Use a regular expression to match the beginning of the string, or white space separating words, plus a single non-whitespace character; use parentheses to mark "match groups". Write a function that takes a match object, and returns the white space match group unchanged and the non-whitespace character match group in upper case. Then use re.sub() to replace the patterns. This one does not have the punctuation problems of the first solution, nor does it redo the white space like my first solution. This one produces the best result.

import re
s = 'the brown fox'

def repl_func(m):
    """process regular expression match groups for word upper-casing problem"""
    return m.group(1) + m.group(2).upper()

s = re.sub("(^|\s)(\S)", repl_func, s)


>>> re.sub("(^|\s)(\S)", repl_func, s)
"They're Bill's Friends From The UK"

我很高兴我研究了这个答案。我不知道re.sub()可以接受函数!您可以在re.sub()中进行非平凡的处理以产生最终结果!

一个快速函数适用于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.

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

我非常喜欢这个答案:

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