문제

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