Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 957
Yuta73 Avatar asked Jun 04 '26 00:06

Yuta73


2 Answers

string is not a type of tuple. Infact both belongs to different class. How in statement will be evaluated is based on the __contains__() magic function defined within there respective class.

Read How do you set up the contains method in python, may be you will find it useful. To know about magic functions in Python, read: A Guide to Python's Magic Methods

like image 52
Moinuddin Quadri Avatar answered Jun 06 '26 15:06

Moinuddin Quadri


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
like image 30
Cameron Lee Avatar answered Jun 06 '26 13:06

Cameron Lee