习惯于写 JavaScript, 当用 python 判断字符串是否包含某子串, 第一时间想到 indexOf, 果然 python 字符串确实有 index 方法.
Python index() 方法检测字符串中是否包含子字符串 str , 如果指定 beg(开始) 和 end(结束) 范围, 则检查是否包含在指定范围内. 如果 str 不在 string 中会报一个异常.
- >>> "javap|python|ruby".index("python")
- 6
- >>> "javap|python|ruby".index("pythonic")
- Traceback (most recent call last):
- File "<input>", line 1, in <module>
- ValueError: substring not found
index() 方法是可用的, 但如果 str 不在 string 中会报一个异常, 就需要写一个方法把这 index 产生的错误包起来, 再把返回一个数值或真假判断.
这就不 pythonic 了. 好在 python 有其它更简单的方法:
in 运算符
- >>> longstring = "www.mzh.ren"
- ... substring = "mzh"
- ... if substring in longstring:
- ... print("找到子串")
- ... else:
- ... print("未找到子串")
- ...
in 运算符会调用对象内置的__contains__ 方法, 该运算符也可用于 list,tuple 等对象.
String.find() 方法
- >>> "javap|python|ruby".index("python")
- 6
- >>> "javap|python|ruby".find("python")
- 6
- >>> "javap|python|ruby".find("pythonic")
- -1
String.find() 与 String.index() 使用上类似, 只是 find 在未找到字串时, 会返回 - 1, 如果你不想 try catch 错误, 你应该选用 find().
正则表达式
正则表达式提供了一种更加灵活也更复杂的检查字符串的匹配方法.
Python 内置正则表达式模块 re.re 模块包含一个名为 search 函数, 我们可以使用它来匹配子串, 如下:
- from re import search
- longstring = "http://www.mzh.ren"
- substring = "mzh.ren"
- if search(substring, longstring):
- print("找到子串!")
- else:
- print("未找到字串!")
参考资料
Python: Check if String Contains Substring
来源: http://www.mzh.ren/python-check-string-contains-substring.html