s = 'the brown fox'

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

S应为:

'The Brown Fox'

最简单的方法是什么?


当前回答

你可以试试这个。简单而利落。

def cap_each(string):
    list_of_words = string.split(" ")

    for word in list_of_words:
        list_of_words[list_of_words.index(word)] = word.capitalize()

    return " ".join(list_of_words)

其他回答

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

我想补充一下@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)

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

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

输出:

This Is A Test String

不要忽视空白的保留。如果你想处理“fred flinstone”,你得到的是“fred flinstone”而不是“fred flinstone”,你已经破坏了你的空白空间。上面的一些解决方案会丢失空白。这里有一个解决方案,适用于Python 2和3,并保留了空白。

def propercase(s):
    return ''.join(map(''.capitalize, re.split(r'(\s+)', s)))

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

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

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

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

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()中进行非平凡的处理以产生最终结果!