1

Lets say I have

a = "FIFA 13"

then I writing

"bla" and "13" in a

And result is true... Why? bla is not in the a

7
  • 3
    What you mean is: "bla" in a and "13" in a Commented Oct 31, 2012 at 21:54
  • 2
    If programming was like speaking english, then the amount of bugs in a software would decrease significantly. Commented Oct 31, 2012 at 21:55
  • 4
    @Fred That's very, very debatable. English is highly ambiguous, an extremely undesirable attribute for programming languages. Commented Oct 31, 2012 at 21:56
  • 1
    @Fred - I think the opposite is infinitely more likely. Spoken language, especially English, is far too ambiguous. Commented Oct 31, 2012 at 21:56
  • 1
    and besides ... python is pretty dang close ;P Commented Oct 31, 2012 at 21:57

4 Answers 4

8

Your boolean expression is being evaluated as ("bla") and ("13" in a), non-empty strings evaluate as true, so if "13" in a is true then the entire expression will evaluate as true.

Instead, use all():

all(x in a for x in ("bla", "13"))

Or just check both separately:

"bla" in a and "13" in a
Sign up to request clarification or add additional context in comments.

Comments

3

You should use

In [1]: a = "FIFA 13"

In [2]: "bla" in a and "13" in a
Out[2]: False

Comments

2

"bla" is true

"13" in a is true

Hence, "bla" and "13" in a is true

What you wanted to write is probably : ("bla" in a) and ("13" in a)

2 Comments

You don't need parentheses here. The in operator has a higher precedence than the and operator. See: docs.python.org/2/reference/expressions.html#summary
I know, it's only for clarity since the person who asked is not familiar with that.
2

Your code isn't interpreted like it is read:

("bla") and ("13" in a)

"bla" is truthy, so it automatically evaluates to True. "13" in a might be True. False and True evaluates to True, so "bla" isn't really taken into consideration.

You have to be a bit more explicit:

'bla' in a and '13' in a

Or you can use an unreadable one-liner:

all(map(a.__contains__, ('bla', '13')))

For a short-circuiting one-liner, I think you'll have to use itertools.imap instead of map..

1 Comment

we can also use operator.contains(), all(map(lambda x:contains(a,x),("bla","12")))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.