Py学习  »  Python

压缩if循环python

CFD • 5 年前 • 1337 次点击  

title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings'
title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows'
title_case('the quick brown fox') # should return: 'The Quick Brown Fox'

解决方案可以是:

def title_case(title, minor_words=''):
    title = title.capitalize().split()
    minor_words = minor_words.lower().split()
    return ' '.join([word if word in minor_words else word.capitalize() for word in title])

如果'word'在'minor_words'中,请加入'minor_words'==>这不是我们想要的。我们想加入“头衔”

我试着用这个和不用这个写“小词”,结果是一样的。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53933
 
1337 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Barmar
Reply   •   1 楼
Barmar    5 年前

如果'word'在'minor_words'中,请加入'minor_words'

word if word in minor_words 意思是如果 word 是在 minor_words 单词 (这是来自 title

else word.capitalize() 意思是如果 单词 小词 ,我们加入大写的单词。

为什么会有 =''

小词 参数。在上一个示例中,您只使用一个参数调用函数:

title_case('the quick brown fox')

title_case('the quick brown fox', '')

如果没有默认值,您将得到一个错误,即没有提供足够的参数。