Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

int - Python: False vs 0

In PHP you use the === notation to test for TRUE or FALSE distinct from 1 or 0.

For example if FALSE == 0 returns TRUE, if FALSE === 0 returns FALSE. So when doing string searches in base 0 if the position of the substring in question is right at the beginning you get 0 which PHP can distinguish from FALSE.

Is there a means of doing this in Python?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Python,

  • The is operator tests for identity (False is False, 0 is not False).

  • The == operator which tests for logical equality (and thus 0 == False).

Technically neither of these is exactly equivalent to PHP's ===, which compares logical equality and type - in Python, that'd be a == b and type(a) is type(b).

Some other differences between is and ==:

Mutable type literals

  • {} == {}, but {} is not {} (and the same holds true for lists and other mutable types)
  • However, if a = {}, then a is a (because in this case it's a reference to the same instance)

Strings

  • "a"*255 is not "a"*255", but "a"*20 is "a"*20 in most implementations, due to how Python handles string interning. This behavior isn't guaranteed, though, and you probably shouldn't be using is in this case. "a"*255 == "a"*255 and is almost always the right comparison to use.

Numbers

  • 12345 is 12345 but 12345 is not 12345 + 1 - 1 in most implementations, similarly. You pretty much always want to use equality for these cases.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...