Re:Code Like a Pythonista: Idiomatic Python
by epenn on Saturday October 22, 2011 @01:55PM
(#3143942)
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.
Re:Code Like a Pythonista: Idiomatic Python
by donatzsky on Sunday October 23, 2011 @02:08PM
(#3146788)
I don't know. I'd argue that
if c not in s: ...
is more explicit (and readable) than if s.find(c) == -1: ...
Re:Code Like a Pythonista: Idiomatic Python
by klenwell on Saturday October 22, 2011 @02:59PM
(#3144089)
You just made my weekend. I've been doing Python for a while and am well acquainted with the "item in list" idiom but did not know it could be used for find. That str.find syntax has always bothered me.
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.
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.