测试子串的字符串? [重复]

时间:2022-05-23 19:18:44

This question already has an answer here:

这个问题在这里已有答案:

Is there an easy way to test a Python string "xxxxABCDyyyy" to see if "ABCD" is contained within it?

有没有一种简单的方法来测试Python字符串“xxxxABCDyyyy”以查看其中是否包含“ABCD”?

2 个解决方案

#1


187  

if "ABCD" in "xxxxABCDyyyy":
    # whatever

#2


30  

There are several other ways, besides using "in" operator(easiest)

除了使用“in”运算符(最简单)之外,还有其他几种方法

index()

指数()

>>> try :
...   "xxxxABCDyyyy".index("test")
... except ValueError:
...   print "not found"
... else:
...   print "found"
...
not found

find()

找()

>>> if "xxxxABCDyyyy".find("ABCD") != -1:
...   print "found"
...
found

re

回覆

>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
...  print "found"
...
found

#1


187  

if "ABCD" in "xxxxABCDyyyy":
    # whatever

#2


30  

There are several other ways, besides using "in" operator(easiest)

除了使用“in”运算符(最简单)之外,还有其他几种方法

index()

指数()

>>> try :
...   "xxxxABCDyyyy".index("test")
... except ValueError:
...   print "not found"
... else:
...   print "found"
...
not found

find()

找()

>>> if "xxxxABCDyyyy".find("ABCD") != -1:
...   print "found"
...
found

re

回覆

>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
...  print "found"
...
found