python - 带有异常(exception)词列表的标题大小写

标签 python python-3.x

我正在尝试想出一些可以“命名”一串单词的东西。它应该将字符串中的所有单词大写,除非给定的单词不作为参数大写。但不管怎样,第一个词仍然会大写。我知道如何将每个单词大写,但我不知道如何不将异常(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/

相关文章:

python-3.x - 在 headless linux机器上使用python绘制自定义ttf字体

具有多个参数的 python getattr()

python - 为什么输入模块会导出 "submodules"?

python - 两个数据点之间的线性插值

python - Ursina 模块中的 invoke() 做了什么

python - numpy 的 fft 结果的幅度要乘以采样周期?

python - tkinter 如何在任何系统上打开特定文件夹(也包含 .py 脚本)的文件目录?

python - 截断文本文件不会更改文件

python-3.x - 文件上传 flask 的单元测试用例

python - Canvas.Move 不起作用