Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string in...in syntax

Tags:

python

It is strange to see a piece of code using 'str in str in str' syntax, e.g.:

>>> 'test' in 'testtest' in 'testtesttest'
True
>>> 'test' in 'testtest' in 'tb3'
False
>>> 'test' in 'testtesta' in 'testtesttest'
False
>>> 'test' in ('testtest' in 'testtesttest')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    'test' in ('testtest' in 'testtesttest')
TypeError: argument of type 'bool' is not iterable

It seems the 'in...in...' is similar to '<...<...' comparison. But a quick google did not guide me to the official answers. Any help?

like image 407
xis Avatar asked Apr 13 '17 01:04

xis


People also ask

What is string in Python syntax?

Strings are Arrays Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1.

What is %s and %D in Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values.

How do you input a string in Python?

In Python, we use input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function convert it into a string.

What is a string in syntax?

5.1 String Read Syntax. The read syntax for strings is an arbitrarily long sequence of characters enclosed in double quotes ( " ). Backslash is an escape character and can be used to insert the following special characters.

What is %s in string?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string. The %s operator is put where the string is to be specified.


1 Answers

Official answer from the Python documentation:

comp_operator ::=  "<" | ">" | "==" | ">=" | "<=" | "!="
                   | "is" ["not"] | ["not"] "in"

The in keyword is a comparison operator. And "Comparisons can be chained arbitrarily". Note that this isn't restricted to "value comparisons" (>, ==, etc.).

The code in question checks whether each is a substring of the next item in the chain.

like image 99
Arya McCarthy Avatar answered Oct 05 '22 23:10

Arya McCarthy