【发布时间】:2020-12-12 20:24:34
【问题描述】:
我一直在尝试解决 CodeWars 上的一个问题,但遇到了障碍。我知道这不是一种特别“pythonic”的方法(我是初学者)。而且我确信有更有效和更先进的方法可以做到这一点。但我真的只是想了解为什么下面的代码不起作用。如果它们出现在另一个过滤词列表中,我只想将列表的字符串项设为小写。 (忽略删除第一项的代码。那是因为该任务需要以不同的方式处理第一项)。
def title_case(title, minors=''):
title = title.title()
mwds = minors.split()
lst = title.split(" ", 1)
exfirst = lst[1].split()
for wd in exfirst:
wd.lower()
if wd in mwds:
wd.lower()
return exfirst
print(title_case('a clash of KINGS', 'a an the of'))
print(title_case('THE WIND IN THE WILLOWS', 'The In'))
结果:
['Clash', 'Of', 'Kings']
['Wind', 'In', 'The', 'Willows']
预期结果:
['Clash', 'of', 'Kings']
['Wind', 'in', 'the', 'Willows']
【问题讨论】:
-
您的代码格式错误,请修正缩进。
str.lower()返回字符串的小写副本,它不会改变原始字符串。字符串是不可变的。
标签: python list filter lowercase