Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

String Python Comparisons Along

$
0
0

Last time , I talked about python’s boolean operators and and or and what can be confusing about them when “truthy” objects get into the mix. If you haven’t already read it, I would highly recommend it. This article is similar, but looks into something just a little different: the ability to string comparison operators.


String Python Comparisons Along
The Confusing Code

Just like last time, we’ll start off looking at some code that confused someone enough to ask the community about it:

'a' in 'abc' # True True == True # True 'a' in 'abc' == True # False

At a cursory glance, there seems to be something wrong with that it would come up with such a result.But this is caused by a feature of Python that is actually really awesome: the ability to string comparison operators.

Less Confusing Code

This awesome feature of Python that helps us keeps our code more concise allows us to turn this code:

0 < x and x < 100

Into this much more readable code:

0 < x < 100

Python actually allows you to do this type of thing indefinitely:

0 < x < 100 < y < z

Which gets expanded to:

0 < x and x < 100 and 100 < y and y < z

Except that it’s optimized so that each variable only needs to be looked up once.

The Confusing Part

But it doesn’t just work with the < , <= , > , and >= operators. It also includes == , != , is , is not , and in . It’s incredibly useful to include the other operators, but they’re not generally expected to be included (especially not in ).

So, let’s go back to the code example:

'a' in 'abc' == True

Gets effectively expanded to:

'a' in 'abc' and 'abc' == True

To get the effect that we actually were expecting, we need only to wrap the first part in parenthesis:

('a' in 'abc') == True Outro

Some of you may have learned about this cool feature in Python just now, or you may be like me and forgot about it until this brought it up. You may also have already known about it, but I doubt that you were able to figure out the starting code example right away. The feature is great, and can help us express conditions in a clean way that we learned back in elementary or middle school, but you’ve also seen that it can be confusing.

Just keep this feature in the back of your mind when writing conditionals and make sure you keep it doing what you want it to do. When in doubt, paren’ it out!


Viewing all articles
Browse latest Browse all 9596

Trending Articles