by grammati · 15y ago · 0 comments
A lot of the Python scripts that I see at work look like either C programs or glorified batch files. I'll definitely point people to this when they are ready and willing to move on to the next level.
Well done.
Suggestion: one thing I didn't see mentioned is switching from "if s.find(c) == -1: ..." to "if c in s: ...". I see people do that a lot.
I think this is covered implicitly by the two "Use in where possible" sections. Although as Tim Peter's The Zen of Python states, which is also quoted in the tutorial, "explicit is better than implicit." If people are doing that despite knowledge of the in keyword then I suppose that just proves Tim's point.
if c not in s: ...
is more explicit (and readable) than if s.find(c) == -1: ...Still, I had to test just to be sure:
test_cases = [
# haystack, needle, expect
('abcdefg', 'a', True),
('abcdefg', 'b', True),
('abcdefg', 'bcd', True),
('abcdefg', 'h', False),
]
for haystack,needle,expect in test_cases:
# find version
is_found = haystack.find(needle) != -1
# in version
is_in = needle in haystack
# confirm
print haystack, needle, expect, '-->', (is_found, is_in)
assert is_found == expect
assert is_found == is_in
Passed! Thanks.