测试字符串是否包含子串

2024-04-24 14:32:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 方法字符串abcdxxxxabcdyyyy
2条回答
if "ABCD" in "xxxxABCDyyyy":
    # whatever

除了使用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

相关问题 更多 >