带有例外词列表的标题大小写

2024-06-26 14:25:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图想出一些东西,将“标题”一串字。它应该将字符串中的所有单词大写,除非给定的单词不作为参数大写。但是不管怎样,第一个单词还是大写的。我知道如何大写每个单词,但我不知道如何不大写例外。有点迷茫,在谷歌上找不到太多。在

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

或者

^{pr2}$

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

示例:titlemaker('a man and his dog','a and')应返回“a man and his dog”


Tags: and字符串标题参数returntitledef单词
3条回答

试试这个:

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')

输出:

^{pr2}$
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')这样的情况下会失败。如果他们是混血儿的话

^{pr2}$
def titleize(text, exceptions):
    return ' '.join([word if word in exceptions else word.title()
                     for word in text.split()]).title()

相关问题 更多 >