如何判断一个子串是否在另一个字符串中
我有一个子字符串:
substring = "please help me out"
我还有另一个字符串:
string = "please help me out so that I could solve this"
我该怎么用Python来检查这个substring
是否是这个string
的一部分呢?
10 个回答
13
如果你想要的不仅仅是对错(真或假),那么使用 re 模块会更合适,比如这样:
import re
search="please help me out"
fullstring="please help me out so that I could solve this"
s = re.search(search,fullstring)
print(s.group())
s.group()
这个命令会返回字符串 "please help me out"。
21
foo = "blahblahblah"
bar = "somethingblahblahblahmeep"
if foo in bar:
# do something
顺便提一下,尽量不要把变量命名为 string
,因为Python有一个标准库也叫这个名字。如果在一个大项目中这样命名,可能会让人感到困惑。所以,避免这种命名冲突是个好习惯。
171
使用 in
关键字时,可以这样理解:substring in string
的意思是检查一个小字符串(substring)是否包含在另一个大字符串(string)里面。
>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True