对字符串进行标题化,但有例外

2024-09-26 18:15:37 发布

您现在位置:Python中文网/ 问答频道 /正文

Python中是否有一种标准的方法来对字符串进行titlecase(即单词以大写字符开头,所有剩余的大小写字符都是小写的),但将诸如andinof这样的项目保留为小写?


Tags: andof项目方法字符串in标准字符
3条回答

这有几个问题。如果使用split和join,一些空白字符将被忽略。内置的大写和标题方法不会忽略空格。

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

有以下方法:

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

没有小写项目选项。你必须自己编写代码,可能需要使用一个你想放低的文章列表。

使用titlecase.py模块!只对英语有效。

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

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

相关问题 更多 >

    热门问题