Вопрос

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