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

标签 python string title-case

在 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

关于python - 对带有异常的字符串进行标题化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3728655/

相关文章:

python - 如何消除 matplotlib 创建的烛台图表中的差距?

Java:如何将字符串与 toString() 的返回值进行比较

java - JTextField 清算时的值(value)迷失

c - 在文件名中添加数字

php - 使所有单词小写,每个单词的第一个字母大写

php - 在 SQL 语句中使用标题大小写

SQL Server : Make all UPPER case to Proper Case/Title Case

python - 错误 'long' 对象没有属性 'fetchall'

python - 从字典中按位置获取键值

python - 在Python中从句子中删除单词但不删除子词