Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 测试字符串的子字符串_Python_String - Fatal编程技术网

Python 测试字符串的子字符串

Python 测试字符串的子字符串,python,string,Python,String,有没有一种简单的方法来测试Python字符串“xxxxABCDyyyy”以查看其中是否包含“ABCD”?除了在操作符中使用之外,还有其他几种方法(最简单): if "ABCD" in "xxxxABCDyyyy": # whatever index() find() re 但是,最后一个需要在一般情况下调用andre.escape。这在这里起作用,但如果您针对非字符串进行测试,则可能不会给出预期的结果。例如,如果针对字符串列表进行测试(如果[“xxxxabcdyyyy”]中的“ABCD

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

除了在操作符中使用
之外,还有其他几种方法(最简单):

if "ABCD" in "xxxxABCDyyyy":
    # whatever
index()

find()

re


但是,最后一个需要在一般情况下调用and
re.escape
。这在这里起作用,但如果您针对非字符串进行测试,则可能不会给出预期的结果。例如,如果针对字符串列表进行测试(如果[“xxxxabcdyyyy”]
中的“ABCD”可能使用
进行测试),这可能会自动失败。@Greenmart如果知道这是一个列表,只需在列表[0]中说
如果“ABCD”
>>> try:
...   "xxxxABCDyyyy".index("test")
... except ValueError:
...   print "not found"
... else:
...   print "found"
...
not found
>>> if "xxxxABCDyyyy".find("ABCD") != -1:
...   print "found"
...
found
>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
...  print "found"
...
found