def censor_string(txt, lst, char):
return " ".join([char*len(i) for i in txt.split() if i in lst else i])
print(censor_string("The cow jumped over the moon.", ["cow", "over"], "*"))
Asked
Active
Viewed 99 times
-2

Balaji Ambresh
- 4,977
- 2
- 5
- 17

Tubii
- 13
- 2
4 Answers
1
The list comprehension syntax is this:
[expression for ... in iterable if something]
while the if
clause being optional and used only for filtering. So you can't have an else
there. But, you have control over the expression. A conditional expression is also an expression so you can write something like this:
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"], "*"))
to achieve your desired result:
The *** jumped **** the moon.

Asocia
- 5,935
- 2
- 21
- 46
0
There are two places where you can put conditionals in a list comprehension:
[ 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
so the correct version of yours would be
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"], "*"))
to get
The *** jumped **** the moon.

Patrick Artner
- 50,409
- 9
- 43
- 69
-1
Here you go:
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"], "*"))
Output
The *** jumped **** the moon.

Balaji Ambresh
- 4,977
- 2
- 5
- 17
-
Isn't it identical with another answer? – Olvin Roght Jul 28 '20 at 20:24
-
1@OlvinRoght It seems to be. But, I had no idea about the other code till I posted my answer. – Balaji Ambresh Jul 28 '20 at 20:26
-3
You have to write
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"], "*"))

Olvin Roght
- 7,677
- 2
- 16
- 35

awasi
- 369
- 1
- 9
-
1@OlvinRoght I downvoted because it doesn't explain what the problem is and how it solves it. *"You have to write this"* shouldn't considered to be valid explanation. And most of the time, the downvotes on the posts like this one simply does nothing because people tend to upvote if a *correct* answer is downvoted. – Asocia Jul 28 '20 at 20:51