在Python中检查字符串是否包含子字符串

字符串操作是编程的重要组成部分。最流行的字符串操作之一是检查字符串是否包含指定的子字符串。从另一个角度来看,如果给定的字符串存在于指定的字符串中。Python提供了不同的方法来检查字符串是否包含子字符串。在本教程中,我们将研究如何在Python中检查给定的字符串是否包含指定的子字符串。

null

与接线员核对

在PYthon中,检查字符串是否包含子字符串的最简单、最实用的方法是使用in运算符。in运算符用于检查指定的数据是否存在于易于用于字符串的完整数据中。此检查根据情况返回True或False。

mystring = "pythontect"substring="tect"if substring in mystring:   print("tect exist in pythontect")else:   print("tect do not exist in pythontect")

使用String.index()方法检查

Python string type提供index()方法来查找指定字符串的索引。index方法由字符串变量或字符串数据提供,如果指定的字符串包含提供的子字符串,则返回正数。如果指定的字符串不包含给定的子字符串,则结果是ValueError异常,这意味着指定的字符串不包含给定的子字符串。

mystring = "pythontect"
substring="tect"

try:   mystring.index(substring)except ValueError:   print("Not found")else:   print("Given substring found in given string")

使用String.find()方法检查

字符串类型提供的另一个方法是find()方法。find()方法与index()方法非常相似。在给定的字符串中搜索指定的子字符串,如果找到该子字符串,则返回第一个字符的索引号。如果找不到-1返回表示找不到它。find()方法比index()方法更易于使用。

mystring = "pythontect"
substring="tect"

if mystring.find(substring)>-1:
   print("tect exist in pythontect")
else:
   print("tect do not exist in pythontect")

用正则表达式检查

正则表达式或简单的Regex用于匹配指定字符串的文本或字符串。Regex用于定义模式并在指定的文本或字符串中进行搜索。Regex还可以用于查找字符串是否包含指定的子字符串。regex模块在Python中被命名为re。re模块提供的搜索方法用于匹配正则表达式。

import remystring = "pythontect"
substring="tect"if re.search(substring,mystring):   print("tect exist in pythontect")else:
   print("tect do not exist in pythontect")
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享