質問

In python a is:

a = "XPZC"

Why is following False in python?

(str(a)[:2] == ("YP" or "XP"))
役に立ちましたか?

解決

This is because ("YP" or "XP") resolves to "YP" because it is asking to return whether "YP" or "XP" resolve to True.

In this case the 'or' is short circuited (since "YP" is not False, "XP" is not evaluated). It returns the non-False value of "YP" which is... "YP"

Also a[:2] is equal to XP. Also, you don't need to call str() since a is a string.

>>> a = "XPZC"
>>> a[:2]
'XP'
>>> "YP" or "XP"
'YP'

You probably want to use in:

>>> a[:2] in ("YP", "XP")
True

or, just check two conditions using or:

>>> s = a[:2]
>>> s == "YP" or s == "XP"
True

他のヒント

(str(a)[:2] in ["YP", "XP"])

"YP" or "XP" returns 'YP'

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top