在 Python 中是否有标准的方法来标题字符串(即单词以大写字符开头,所有剩余的大小写字符都小写)但留下诸如 and
、in
之类的文章, 和 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/