python - 对带有异常的字符串进行标题化

在 Python 中是否有标准的方法来标题字符串(即单词以大写字符开头,所有剩余的大小写字符都小写)但留下诸如 andin 之类的文章, 和 of 小写?

最佳答案

这有一些问题。如果使用 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

https://stackoverflow.com/questions/3728655/

相关文章:

python - 为什么循环导入似乎在调用堆栈中更靠前,但在更靠下的位置引发 ImportError

python - 在 CentOS 中安装 python 2.6

python - SQLAlchemy ORM 转换为 pandas DataFrame

python - 如何删除字符串中的前导零和尾随零? Python

python - 使用 PyInstaller (--onefile) 捆绑数据文件

python - “模块”没有属性 'urlencode'

python - 如何绘制正态分布

python - 来自 os.listdir() 的非字母数字列表顺序

python - 非 ASCII 字符的语法错误

python - 如何检查文件是否是有效的图像文件?