我有一个子字符串:
substring = "please help me out"
Run Code Online (Sandbox Code Playgroud)
我有另一个字符串:
string = "please help me out so that I could solve this"
Run Code Online (Sandbox Code Playgroud)
如何查找是否substring是string使用Python 的子集?
Mar*_*coS 166
用in:substring in string:
>>> substring = "please help me out"
>>> string = "please help me out so that I could solve this"
>>> substring in string
True
Run Code Online (Sandbox Code Playgroud)
Amb*_*ber 20
foo = "blahblahblah"
bar = "somethingblahblahblahmeep"
if foo in bar:
# do something
Run Code Online (Sandbox Code Playgroud)
(顺便说一句 - 尝试不命名变量string,因为有一个同名的Python标准库.如果你在一个大型项目中这样做,你可能会混淆人们,因此避免这样的冲突是一个很好的习惯.)
小智 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())
Run Code Online (Sandbox Code Playgroud)
s.group() 将返回字符串"请帮助我".
小智 9
我想如果你正在考虑如何在技术面试中做这个,他们不希望你使用Python的内置函数,in或者find这很可怕,但确实会发生:
string = "Samantha"
word = "man"
def find_sub_string(word, string):
len_word = len(word) #returns 3
for i in range(len(string)-1):
if string[i: i + len_word] == word:
return True
else:
return False
Run Code Online (Sandbox Code Playgroud)
您也可以尝试使用find()方法.它确定字符串str是出现在字符串中还是出现在字符串的子字符串中.
str1 = "please help me out so that I could solve this"
str2 = "please help me out"
if (str1.find(str2)>=0):
print("True")
else:
print ("False")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
212936 次 |
| 最近记录: |