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.

1 Comment »

  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

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)