Python Trick: Check for Substring
December 26th, 2008
Today I’d like to show you a quick hint that might be obvious, but it took me quite some time of Python programming to figure it out.
You probably know that you can test if a list, tuple, or dict contains an item by testing the expression “item in list” or “item not in list”. I never realized that this would work for strings as well.
I was always writing code like:
string = 'Hi there' # True example string = 'Good bye' # False example if string.find('Hi') != -1: print 'Success!'
It’s kinda ugly code but it didn’t mind at all since I found otu that it is completely equivalent to do “if substring in string”:
string = 'Hi there' # True example string = 'Good bye' # False example if 'Hi' in string: print 'Success!'
Much cleaner and simpler. Might be obvious to 99% of the population, but I wish I’d known about it sooner.






[…] to check if a certain substring (in my case ‘ FROM ‘) is present in a SQL query string when I found this blog entry. Just for fun I decided to have a look at how fast these checks would be compared to […]
Pingback by Python: check for substring speed | Patrick's playground — June 29, 2009 @ 5:07 pm
Thanks for posting this tip…
This tip really helped me
Comment by Balaji — August 28, 2010 @ 12:29 pm
Thank you so much, what a great tip. I haven’t written any Python in ages and am just starting to get back into it.
Don’t worry, it wasn’t obvious to me either, btw
Comment by mikey — October 15, 2010 @ 12:18 am
Thax a lot … this will help me a lot in my project going on now
Comment by nithin — December 16, 2010 @ 12:06 pm
thanks a lot
Comment by snow — October 5, 2011 @ 11:15 am
aha sem nasel tole Šivilja Kranj
Comment by bobicu — November 7, 2011 @ 9:58 pm