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)

其他回答

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

大写的单词…

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

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

以防你想裁员

# 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