0

Let's say I have a string

S='Let us start attending Stanford University Lectures'

Now if I want to have all the words that have an 's' or 'S' in them then the following list comprehension

[x for x in S if 'S' or 's' in x])

I get the following

['L', 'e', 't', ' ', 'u', 's', ' ', 's', 't', 'a', 'r', 't', ' ', 'a', 't', 't', 'e', 'n', 'd', 'i', 'n', 'g', ' ', 'S', 't', 'a', 'n', 'f', 'o', 'r', 'd', ' ', 'U', 'n', 'i', 'v', 'e', 'r', 's', 'i', 't', 'y', ' ', 'L', 'e', 'c', 't', 'u', 'r', 'e', 's']

but when I change the list comprehension to

[x for x in S if 'S' in x])

I get the following

['S']

Why am I getting incorrect results?

Danny Staple
  • 7,101
  • 4
  • 43
  • 56
  • 2
    The second example *is* correct because you only ask for upper-case 'S'. The first example does not work as you expect, because `'S' or 's' in x` is always true. – mkrieger1 Jun 10 '20 at 10:07
  • You could have used `'S' in x or 's' in x` instead. – mkrieger1 Jun 10 '20 at 10:08
  • And if you want to get a list of *words*, you need to *split* the string into words first. Iterating over a string gives the individual characters, as you have seen. – mkrieger1 Jun 10 '20 at 10:10
  • its actually my mistake. Should have been using it on a list instead of a string. – jackreacher80 Jun 10 '20 at 10:11
  • Sounds like you only want a list of words with 's' in them: my_str = 'Let us start attending Stanford University Lectures' [x for x in my_str.split(' ') if 's' in x.lower()] – eNc Jun 10 '20 at 10:18

0 Answers0