带有例外单词列表的标题格式

CDo*_*Dog 5 python python-3.x

我试图想出一些可以为一串单词“加标题”的东西。它应该将字符串中的所有单词大写,除非给定的单词作为参数不大写。但无论如何,第一个单词仍会大写。我知道如何将每个单词大写,但我不知道如何不将例外情况大写。有点迷失从哪里开始,在谷歌上找不到太多。

  def titlemaker(title, exceptions):
      return ' '.join(x[0].upper() + x[1:] for x in title.split(' '))
Run Code Online (Sandbox Code Playgroud)

或者

return title.title()
Run Code Online (Sandbox Code Playgroud)

但我发现撇号后的字母会大写,所以我认为我不应该使用它。关于我应该如何考虑例外情况的任何帮助都会很好

示例: titlemaker('a man and his dogs', 'a and') 应返回 'A Man and His Dog'

Mat*_*hew 4

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"
Run Code Online (Sandbox Code Playgroud)

上面假设输入字符串和异常列表的情况相同(如您的示例中所示),但在诸如“titlemaker('a man And his dogs','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"
Run Code Online (Sandbox Code Playgroud)