python - Python 中的子字符串搜索

标签 python string substring

我想了解以下语句的工作原理:

if ("ssh" or "telnet") in connection_type:
 ...

这似乎工作类似于:

if any(substr in connection_type for substr in ["ssh", "telnet"]):
...

这两种说法有什么区别吗?谢谢!

最佳答案

是的,有区别。

第一个似乎有效,但没有。

>>> connection_type = 'ssh'
>>> ("ssh" or "telnet") in connection_type
True

>>> connection_type = 'telnet'
>>> ("ssh" or "telnet") in connection_type
False

这是为什么呢? Python 中的 or 运算符返回操作数中的第一个 True 值,如果所有操作数的计算结果均为 False,则返回最后一个值 - 这就是它的原因仅适用于“ssh”。您可以将 or 想象成其他语言的三元运算符:

first or second

就像:

bool(first) ? first : second

第二个是对的。

如果connection_type是整个单词“telnet”或“ssh”,您还可以这样做:

if connection_type in ('ssh', 'telnet'):
    ...

如果“telnet”或“ssh”只是connection_type的子字符串,您还可以使用正则表达式:

if re.search(r'ssh|telnet', connection_type):
    ...

关于python - Python 中的子字符串搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42030601/

相关文章:

c++ - 删除 vector 中的字符串

batch-file - 在批处理文件中执行子字符串的最佳方法是什么?

python - 不同环境下搜索结果不同

python - 根据相邻坐标操作 pandas 数据框

python - 致命的 Python 错误 : init_sys_streams: can't initialize sys standard streams AttributeError: module 'io' has no attribute 'OpenWrapper'

python - 如何从函数定义中设置函数属性?

c - 将 .txt 文件拆分为单词并将每个单词存储在数组中

c# - 随机字符串 |密码加盐建议

ios - 在 Swift 中使用范围从属性字符串返回子字符串

tcsh 中匹配的字符串/子字符串