jeudi 11 juin 2015

Check if a string is a substring of another in Python

I learned a simple yet extremely useful trick in Python lately. I think it was while watching a talk from Raymond Hettinger.

To find a substring from a string in Python, you do not need str.find nor str.index. You can instead use in operator:

In [5]: if 'bar' in 'foobarbaz': print('bam!')
bam!

Notice that it is not as logical as you may think. As you may know, a str is a particular form of list. You can access a character or a range just like a list:

In [6]: 'foobarbaz'[2]
Out[6]: 'o'

You can iterate on it:

In [7]: for i, c in enumerate('foobarbaz'):
   ...:     print('Char {0} is {1}.'.format(i, c))
      ...:
      Char 0 is f.
      Char 1 is o.
      Char 2 is o.
      Char 3 is b.
      Char 4 is a.
      Char 5 is r.
      Char 6 is b.
      Char 7 is a.
      Char 8 is z.

But in cannot be used to check if a list is a subset of another:

In [9]: [2, 3] in [1, 2, 3]
Out[9]: False

That's why I was a bit amazed!

That’s all for today: I realized I have a some scripts to simplify using this nice feature!