给字符串加上标题框(带例外) [英] Titlecasing a string with exceptions
本文介绍了给字符串加上标题框(带例外)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Python中是否有一种标准的方式来对字符串加上大小写(即单词以大写字母开头,所有其余的大写字母都为小写字母),但是却保留诸如and
,in
和of
的文章为小写字母?
Is there a standard way in Python to titlecase a string (i.e. words start with uppercase characters, all remaining cased characters have lowercase) but leaving articles like and
, in
, and of
lowercased?
推荐答案
这有一些问题.如果使用拆分和合并,则某些空格字符将被忽略.内置的大写和标题方法不会忽略空格.
There are a few problems with this. If you use split and join, some white space characters will be ignored. The built-in capitalize and title methods do not ignore white space.
>>> 'There is a way'.title()
'There Is A Way'
如果句子以文章开头,则不希望标题的第一个单词小写.
If a sentence starts with an article, you do not want the first word of a title in lowercase.
记住这些:
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
这篇关于给字符串加上标题框(带例外)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文