Python Conundrum String Theory

The following code should print MyWords after removing SpamWords [0]. However; instead of returning "yes", instead, returning "No". Why does it return "No"?

MyWords = "Spam yes"
SpamWords = ["SPAM"]
SpamCheckRange = 0
print ((MyWords.upper()).split()).remove(SpamWords[SpamCheckRange])
+3
source share
2 answers

Because remove- this is a method that modifies the mutable list object that it called and returns None.

l= MyWords.upper().split()
l.remove(SpamWords[SpamCheckRange])
# l is ['YES']

Perhaps you want to:

>>> [word for word in MyWords.split() if word.upper() not in SpamWords]
['yes']
+7
source

removeis a method list( str.splitreturns a list), not str. It mutates the original list (deletes what you pass in) and returns None, not the modified list.

0
source

Source: https://habr.com/ru/post/1732420/


All Articles