给定两个字符串, 检查s2中是否存在s1。
例子:
Input : s1 = geeks s2=geeks for geeks
Output : yes
Input : s1 = geek s2=geeks for geeks
Output : yes
我们可以迭代检查每个单词, 但是Python为我们提供了一个内置函数find()
它检查字符串中是否存在子字符串, 这是一行完成的。
如果未找到, find()函数将返回-1, 否则将返回第一个匹配项, 因此使用此函数可以解决此问题。
方法1:使用用户定义的功能。
# function to check if small string is
# there in big string
def check(string, sub_str):
if (string.find(sub_str) = = - 1 ):
print ( "NO" )
else :
print ( "YES" )
# driver code
string = "geeks for geeks"
sub_str = "geek"
check(string, sub_str)
输出如下:
YES
方法2:使用” count()”方法:-
def check(s2, s1):
if (s2.count(s1)> 0 ):
print ( "YES" )
else :
print ( "NO" )
s2 = "A geek in need is a geek indeed"
s1 = "geek"
check(s2, s1)
输出如下:
YES
方法3:使用正则表达式
RegEx可用于检查字符串是否包含指定的搜索模式。 Python有一个称为的内置程序包re, 可用于正则表达式。
# When you have imported the re module, you can start using regular expressions.
import re
# Take input from users
MyString1 = "A geek in need is a geek indeed"
MyString2 = "geek"
# re.search() returns a Match object if there is a match anywhere in the string
if re.search( MyString2, MyString1 ):
print ( "YES, string '{0}' is present in string '{1}' " . format (MyString2, MyString1))
else :
print ( "NO, string '{0}' is not present in string {1} " . format (MyString2, MyString1) )
输出如下:
YES, string 'geek' is present in string 'A geek in need is a geek indeed'
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
来源:
https://www.srcmini02.com/70497.html