class NoisyString(str):def __contains__(self, other):print(f'testing if "{other}" in "{self}"')return super(NoisyString, self).__contains__(other)
ns = NoisyString('a string with a substring inside')
现在:
>>> 'substring' in nstesting if "substring" in "a string with a substring inside"True
不要使用find和index来测试“包含”
不要使用以下字符串方法来测试“包含”:
>>> '**foo**'.index('foo')2>>> '**foo**'.find('foo')2
>>> '**oo**'.find('foo')-1>>> '**oo**'.index('foo')
Traceback (most recent call last):File "<pyshell#40>", line 1, in <module>'**oo**'.index('foo')ValueError: substring not found
>>> "foo" in "foobar"True>>> "foo" in "Foobar"False>>> "foo" in "Foobar".lower()True>>> "foo".capitalize() in "Foobar"True>>> "foo" in ["bar", "foo", "foobar"]True>>> "foo" in ["fo", "o", "foobar"]False>>> ["foo" in a for a in ["fo", "o", "foobar"]][False, False, True]