带例外的字符串首字母大写

96 投票
9 回答
98214 浏览
提问于 2025-04-16 04:14

在Python中,有没有一种标准的方法可以把一个字符串变成标题格式(也就是每个单词的首字母大写,其他字母小写),但是像andinof这些小词要保持小写呢?

9 个回答

24

这里有一些方法:

>>> mytext = u'i am a foobar bazbar'
>>> print mytext.capitalize()
I am a foobar bazbar
>>> print mytext.title()
I Am A Foobar Bazbar

没有小写的冠词选项。你需要自己编写代码来实现这个功能,可能需要用一个你想要转换为小写的冠词列表。

64

使用 titlecase.py 这个模块吧!这个模块只适用于英语。

>>> from titlecase import titlecase
>>> titlecase('i am a foobar bazbar')
'I Am a Foobar Bazbar'

GitHub地址: https://github.com/ppannuto/python-titlecase

160

这个问题有几个地方需要注意。如果你使用分割和连接的方法,有些空白字符会被忽略。而内置的capitalize和title方法则不会忽略空白字符。

>>> 'There     is a way'.title()
'There     Is A Way'

如果一个句子是以冠词开头的,你不希望标题的第一个单词是小写的。

记住这些要点:

import re 
def title_except(s, exceptions):
    word_list = re.split(' ', s)       # re.split behaves as expected
    final = [word_list[0].capitalize()]
    for word in word_list[1:]:
        final.append(word if word in exceptions else word.capitalize())
    return " ".join(final)

articles = ['a', 'an', 'of', 'the', 'is']
print title_except('there is a    way', articles)
# There is a    Way
print title_except('a whim   of an elephant', articles)
# A Whim   of an Elephant

撰写回答