Python一行if-else语句SyntaxError,错误位于;“否则”;,有什么问题吗? def-censor_字符串(txt、lst、char): 返回“.join”([char*len(i)表示txt.split()中的i,如果我在lst else i]) 打印(审查字符串(“奶牛跳过了月亮。”,[“奶牛”,“越过”],“*”))
你必须写Python一行if-else语句SyntaxError,错误位于;“否则”;,有什么问题吗? def-censor_字符串(txt、lst、char): 返回“.join”([char*len(i)表示txt.split()中的i,如果我在lst else i]) 打印(审查字符串(“奶牛跳过了月亮。”,[“奶牛”,“越过”],“*”)),python,if-statement,Python,If Statement,你必须写 def censor_string(txt, lst, char): return " ".join([char*len(i) if i in lst else i for i in txt.split() ]) print(censor_string("The cow jumped over the moon.", ["cow", "over"], "*")) 给你: de
def censor_string(txt, lst, char):
return " ".join([char*len(i) if i in lst else i for i in txt.split() ])
print(censor_string("The cow jumped over the moon.", ["cow", "over"], "*"))
给你:
def-censor_字符串(txt、lst、char):
返回“”
打印(审查字符串(“奶牛跳过了月亮。”,[“奶牛”,“越过”],“*”))
输出
The *** jumped **** the moon.
有两个地方可以在列表中放置条件:
[ AA or BB for elem in sequence if elem something]
^^^^^^^^^^ ^^^^^^^^^^^^^^^^^-- use the element or not in the
^--- what to put into the result result - no ELSE allowed
所以你的正确版本应该是
def censor_string(txt, lst, char):
return " ".join([char*len(i) if i in lst else i for i in txt.split()])
print(censor_string("The cow jumped over the moon.", ["cow", "over"], "*"))
得到
The *** jumped **** the moon.
列表理解语法如下所示:
[expression for ... in iterable if something]
而if
子句是可选的,仅用于过滤。所以你不能在那里有一个else
。但是,您可以控制表达式。条件表达式也是表达式,因此您可以编写如下内容:
def censor_string(txt, lst, char):
return " ".join([char*len(i) if i in lst else i for i in txt.split()])
print(censor_string("The cow jumped over the moon.", ["cow", "over"], "*"))
要达到预期效果,请执行以下操作:
The *** jumped **** the moon.
那个男孩跳到了月球上。
这和另一个答案不一样吗?@OlvinRoght似乎是。但是,在我发布我的答案之前,我对其他代码一无所知。@OlvinRoght我投了反对票,因为它没有解释问题是什么以及如何解决问题。“你必须写这个”不应该被认为是有效的解释。大多数时候,像这样的帖子上的否决票根本没有任何作用,因为如果一个正确的答案被否决,人们倾向于投上一票。