s = 'the brown fox'

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

S应为:

'The Brown Fox'

最简单的方法是什么?


当前回答

使用非均匀空格将字符串大写

我想补充一下@Amit Gupta关于非均匀空间的观点:

从最初的问题中,我们想要大写字符串s = 'the brown fox'中的每个单词。如果字符串s = 'the brown fox'有不均匀的空格。

def solve(s):
    # If you want to maintain the spaces in the string, s = 'the brown      fox'
    # Use s.split(' ') instead of s.split().
    # s.split() returns ['the', 'brown', 'fox']
    # while s.split(' ') returns ['the', 'brown', '', '', '', '', '', 'fox']
    capitalized_word_list = [word.capitalize() for word in s.split(' ')]
    return ' '.join(capitalized_word_list)

其他回答

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

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

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

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

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

只大写第一个字母。

使用非均匀空格将字符串大写

我想补充一下@Amit Gupta关于非均匀空间的观点:

从最初的问题中,我们想要大写字符串s = 'the brown fox'中的每个单词。如果字符串s = 'the brown fox'有不均匀的空格。

def solve(s):
    # If you want to maintain the spaces in the string, s = 'the brown      fox'
    # Use s.split(' ') instead of s.split().
    # s.split() returns ['the', 'brown', 'fox']
    # while s.split(' ') returns ['the', 'brown', '', '', '', '', '', 'fox']
    capitalized_word_list = [word.capitalize() for word in s.split(' ')]
    return ' '.join(capitalized_word_list)

我非常喜欢这个答案:

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