我试图想出一些能够成为" title"一串字。它应该大写字符串中的所有单词,除非给定的单词不作为参数大写。但无论如何,仍然会把第一个词大写。我知道如何利用每个单词,但我不知道如何不利用异常。有点迷失在哪里开始,在谷歌上找不到多少。
def titlemaker(title, exceptions):
return ' '.join(x[0].upper() + x[1:] for x in title.split(' '))
或
return title.title()
但是我发现在撇号后会把一封信大写,所以我不认为我应该使用它。 关于我应该如何考虑异常的任何帮助都很好
示例:titlemaker('一个男人和他的狗',' a和')应该返回' A Man and His Dog'
答案 0 :(得分:3)
def titlemaker(title,exceptions):
exceptions = exceptions.split(' ')
return ' '.join(x.title() if nm==0 or not x in exceptions else x for nm,x in enumerate(title.split(' ')))
titlemaker('a man and his dog','a and') # returns "A Man and His Dog"
以上假设输入字符串和异常列表在相同的情况下(就像在你的例子中一样),但是在诸如`titlemaker('a man and his dog','a and''之类的东西上会失败)。如果他们可能是混合的情况吗,
def titlemaker(title,exceptions):
exceptionsl = [x.lower() for x in exceptions.split(' ')]
return ' '.join(x.title() if nm==0 or not x.lower() in exceptions else x.lower() for nm,x in enumerate(title.split(' ')))
titlemaker('a man and his dog','a and') # returns "A Man and His Dog"
titlemaker('a man AND his dog','a and') # returns "A Man and His Dog"
titlemaker('A Man And His DOG','a and') # returns "A Man and His Dog"
答案 1 :(得分:2)
def titleize(text, exceptions):
return ' '.join([word if word in exceptions else word.title()
for word in text.split()]).title()
答案 2 :(得分:1)
试试这个:
def titleize(text, exceptions):
exceptions = exceptions.split()
text = text.split()
# Capitalize every word that is not on "exceptions" list
for i, word in enumerate(text):
text[i] = word.title() if word not in exceptions or i == 0 else word
# Capitalize first word no matter what
return ' '.join(text)
print titleize('a man and his dog', 'a and')
<强>输出:强>
A Man and His Dog