pythonstringtuplesslicemagic-function

Python newbie clarification about tuples and strings


I just learned that I can check if a substring is inside a string using:

substring in string

It looks to me that a string is just a special kind of tuple where its elements are chars. So I wonder if there's a straightforward way to search a slice of a tuple inside a tuple. The elements in the tuple can be of any type.

tupleslice in tuple

Now my related second question:

>>> tu = 12 ,23, 34,56
>>> tu[:2] in tu
False

I gather that I get False because (12, 23) is not an element of tu. But then, why substring in string works?. Is there syntactic sugar hidden behind scenes?.


Solution

  • A string is not just a special kind of tuple. They have many similar properties, in particular, both are iterators, but they are distinct types and each defines the behavior of the in operator differently. See the docs on this here: https://docs.python.org/3/reference/expressions.html#in

    To solve your problem of finding whether one tuple is a sub-sequence of another tuple, writing an algorithm like in your answer would be the way to go. Try something like this:

    def contains(inner, outer):
      inner_len = len(inner)
      for i, _ in enumerate(outer):
        outer_substring = outer[i:i+inner_len]
        if outer_substring == inner:
          return True
      return False