在Python中,我可以看到关键字in可以有效地用于检查子字符串,如:str1 in str2
无论如何都要做反转版本in,比如有一个(假设)关键字contain来表示str2 contain str1?这是为了编写代码的流程,如:
if str contain "foo":
return 1
elif str contain "bar":
return 2
elif str contain "boo":
return 3
elif str contain "far":
return 4
else
return 5
Run Code Online (Sandbox Code Playgroud)
就个人而言,(假设)上面的代码比使用更具可读性in:
if "foo" in str:
return 1
elif "bar" in str:
return 2
elif "boo" in str:
return 3
elif "far" in str:
return 4
else
return 5
Run Code Online (Sandbox Code Playgroud)
事实上,有一种__contains__方法可以像你描述的那样工作:
>>> 'the quick brown fox'.__contains__('quick')
True
Run Code Online (Sandbox Code Playgroud)
还有一个包含没有下划线的函数:
>>> from operator import contains
>>> contains('the quick brown fox', 'quick')
True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |