rulururu

post Python Trick: Check for Substring

December 26th, 2008

Filed under: Python — Kai @ 7:36 pm

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.

6 Comments »

  1. […] 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

  2. Thanks for posting this tip…

    This tip really helped me :)

    Comment by Balaji — August 28, 2010 @ 12:29 pm

  3. 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

  4. Thax a lot … this will help me a lot in my project going on now :)

    Comment by nithin — December 16, 2010 @ 12:06 pm

  5. thanks a lot :)

    Comment by snow — October 5, 2011 @ 11:15 am

  6. aha sem nasel tole Šivilja Kranj

    Comment by bobicu — November 7, 2011 @ 9:58 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)