我正在尝试想出一些可以“命名”一串单词的东西。它应该将字符串中的所有单词大写,除非给定的单词不作为参数大写。但不管怎样,第一个词仍然会大写。我知道如何将每个单词大写,但我不知道如何不将异常(exception)情况大写。有点不知道从哪里开始,在谷歌上找不到太多东西。
def titlemaker(title, exceptions):
return ' '.join(x[0].upper() + x[1:] for x in title.split(' '))
或
return title.title()
但我发现撇号后的字母会大写,所以我认为我不应该使用它。 任何关于我应该如何考虑异常的帮助都会很好
示例:titlemaker('a man and his dog', 'a and') 应该返回 'A Man and His Dog'
最佳答案
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"
关于python - 带有异常(exception)词列表的标题大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34778986/