开发者

Test a string for a substring [duplicate]

This question already has answers here: Does Python have a string 'contains' substring method? (10 answers) Closed 9 years ago.

Is there an easy way to test a Python string "xxxxABCDyyy开发者_运维技巧y" to see if "ABCD" is contained within it?


if "ABCD" in "xxxxABCDyyyy":
    # whatever


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

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜