739
s = 'the brown fox'

……在这里做点什么……

s应该:

'The Brown Fox'

最简单的方法是什么?

4

22 回答 22

1214

字符串的.title()方法(ASCII 或 Unicode 都可以)这样做:

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

但是,请注意带有嵌入撇号的字符串,如文档中所述。

该算法使用一个简单的独立于语言的单词定义作为一组连续的字母。该定义在许多情况下都有效,但这意味着缩写和所有格中的撇号形成单词边界,这可能不是预期的结果:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
于 2009-10-11T02:04:35.680 回答
227

.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"

来自关于 capwords 的 Python 文档

使用 str.split() 将参数拆分为单词,使用 str.capitalize() 将每个单词大写,并使用 str.join() 连接大写单词。如果可选的第二个参数 sep 不存在或无,则空白字符的运行将替换为单个空格并删除前导和尾随空格,否则 sep 用于拆分和连接单词。

于 2012-09-09T06:03:36.237 回答
118

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

拆分为单词,对拆分组中的每个单词进行初始大写,然后重新加入。这会将分隔单词的空格更改为单个空格,无论它是什么。

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

使用正则表达式匹配字符串的开头,或空格分隔的单词,加上单个非空格字符;使用括号标记“匹配组”。编写一个接受匹配对象的函数,并返回未更改的空白匹配组和大写的非空白字符匹配组。然后用于re.sub()替换图案。这个没有第一个解决方案的标点问题,也没有像我的第一个解决方案那样重做空白。这个产生最好的结果。

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()的处理以产生最终结果!

于 2009-10-11T06:04:11.497 回答
31

以下是不同方法的摘要,它们适用于所有这些输入:

""           => ""       
"a b c"      => "A B C"             
"foO baR"    => "FoO BaR"      
"foo    bar" => "Foo    Bar"   
"foo's bar"  => "Foo's Bar"    
"foo's1bar"  => "Foo's1bar"    
"foo 1bar"   => "Foo 1bar"     

- 最简单的解决方案是将句子拆分为单词并将第一个字母大写,然后将其重新组合在一起:

# Be careful with multiple spaces, and empty strings
# for empty words w[0] would cause an index error, 
# but with w[:1] we get an empty string as desired
def cap_sentence(s):
  return ' '.join(w[:1].upper() + w[1:] for w in s.split(' ')) 

- 如果您不想先将输入字符串拆分为单词,并使用花哨的生成器:

# Iterate through each of the characters in the string and capitalize 
# the first char and any char after a blank space
from itertools import chain 
def cap_sentence(s):
  return ''.join( (c.upper() if prev == ' ' else c) for c, prev in zip(s, chain(' ', s)) )

- 或者不导入 itertools:

def cap_sentence(s):
  return ''.join( (c.upper() if i == 0 or s[i-1] == ' ' else c) for i, c in enumerate(s) )

- 或者您可以使用steveha 的回答中的正则表达式:

# match the beginning of the string or a space, followed by a non-space
import re
def cap_sentence(s):
  return re.sub("(^|\s)(\S)", lambda m: m.group(1) + m.group(2).upper(), s)

现在,如果我们使用单词的定义作为句子的开头或空格后的任何内容,这些是发布的其他一些答案,以及它们无法按预期工作的输入:

  return s.title()

# Undesired outputs: 
"foO baR"    => "Foo Bar"       
"foo's bar"  => "Foo'S Bar" 
"foo's1bar"  => "Foo'S1Bar"     
"foo 1bar"   => "Foo 1Bar"      

  return ' '.join(w.capitalize() for w in s.split())    
  # or
  import string
  return string.capwords(s)

# Undesired outputs:
"foO baR"    => "Foo Bar"      
"foo    bar" => "Foo Bar"      

使用 ' ' 进行拆分将修复第二个输出,但 capwords() 仍然不适用于第一个

  return ' '.join(w.capitalize() for w in s.split(' '))    
  # or
  import string
  return string.capwords(s, ' ')

# Undesired outputs:
"foO baR"    => "Foo Bar"      

小心多个空格

  return ' '.join(w[0].upper() + w[1:] for w in s.split())
# Undesired outputs:
"foo    bar" => "Foo Bar"                 
于 2017-02-28T05:29:03.503 回答
16

@jibberia anwser 的可复制粘贴版本:

def capitalize(line):
    return ' '.join(s[:1].upper() + s[1:] for s in line.split(' '))
于 2012-04-04T14:47:11.497 回答
14

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

只需这样做:

string = "the brown fox"
string[0].upper()+string[1:]
于 2014-08-29T10:13:46.980 回答
11

如果 str.title() 对您不起作用,请自己进行大写。

  1. 将字符串拆分为单词列表
  2. 将每个单词的首字母大写
  3. 将单词连接成一个字符串

单线:

>>> ' '.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)
于 2009-10-11T06:05:41.480 回答
10

如果只想要第一个字母:

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

但是要将每个单词大写:

>>> 'hello world'.title()
'Hello World'
于 2018-02-04T21:11:18.070 回答
7

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

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

仅将第一个字母大写。

于 2017-05-17T12:54:57.017 回答
6

尽管所有答案都已经令人满意,但我将尝试将两个额外的案例与之前的所有案例一起介绍。

如果空间不统一并且您想保持相同

string = hello    world i  am    here.

如果所有字符串都不是从字母开始

string = 1 w 2 r 3g

在这里你可以使用这个:

def solve(s):
    a = s.split(' ')
    for i in range(len(a)):
        a[i]= a[i].capitalize()
    return ' '.join(a)

这会给你:

output = Hello    World I  Am    Here
output = 1 W 2 R 3g
于 2019-10-16T04:44:53.227 回答
4

正如马克指出的那样,您应该使用.title()

"MyAwesomeString".title()

但是,如果想让Django 模板中的第一个字母大写,可以使用:

{{ "MyAwesomeString"|title }}

或使用变量:

{{ myvar|title }}
于 2014-03-16T13:04:49.097 回答
4

建议的方法 str.title() 并非在所有情况下都有效。例如:

string = "a b 3c"
string.title()
> "A B 3C"

而不是"A B 3c".

我认为,最好做这样的事情:

def capitalize_words(string):
    words = string.split(" ") # just change the split(" ") method
    return ' '.join([word.capitalize() for word in words])

capitalize_words(string)
>'A B 3c'
于 2016-11-11T17:57:17.753 回答
2

要将单词大写...

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))
于 2014-01-29T13:47:58.350 回答
2

你可以试试这个。简单整洁。

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)
于 2021-07-08T22:10:43.377 回答
1

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

def propercase(s):
    return ''.join(map(''.capitalize, re.split(r'(\s+)', s)))
于 2017-11-24T21:54:14.213 回答
1

.title() 方法不适用于所有测试用例,因此将 .capitalize()、.replace() 和 .split() 一起使用是每个单词首字母大写的最佳选择。

例如:def caps(y):

     k=y.split()
     for i in k:
        y=y.replace(i,i.capitalize())
     return y
于 2021-01-13T21:19:21.897 回答
0

一个适用于 Python 3 的快速函数

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.
于 2019-12-31T11:34:49.087 回答
0

大写带有非均匀空格的字符串

我想补充@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)
于 2020-02-03T20:37:22.413 回答
0

另一种在线解决方案可能是:

" ".join(map(lambda d: d.capitalize(), word.split(' ')))
于 2022-02-10T19:13:15.263 回答
-1

如果你想缩小规模

# 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
于 2018-03-14T08:44:42.800 回答
-1

您的问题最简单的解决方案,它适用于我的情况:

import string
def solve(s):
    return string.capwords(s,' ') 
    
s=input()
res=solve(s)
print(res)
于 2020-11-07T06:49:07.630 回答
-2

我真的很喜欢这个答案:

@jibberia anwser 的可复制粘贴版本:

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])
于 2013-11-10T20:39:10.693 回答