[英]How do you find a substring of a string in python using no built-in function or slicing
I'm trying to work on a basic python program that is to find a substring of a string in python but the challenge was I can't use built functions or slicing. 我正在尝试在一个基本的python程序上工作,该程序将在python中找到字符串的子字符串,但是挑战是我不能使用内置函数或切片。
MAINSTRING = raw_input('Enter a string : ')
print 'You entered %s' %MAINSTRING
isSubString = raw_input('Enter the substring : ')
print 'You entered %s' %isSubString
if isSubString in MAINSTRING:
print isSubString + " is a substring of " + MAINSTRING
It works but I can't use in
syntax which is the frustrating part. 它的工作原理,但我不能用in
语法这是令人沮丧的。 I also know to use the slicing method in python but my challenge was to break it to the basics. 我也知道在python中使用切片方法,但是我的挑战是将其分解为基础。
Sorry for being so vague, but I just got a hint. 抱歉,我含糊不清,但我只是得到了一个提示。
The complete code consist of two 'for' loops, one for the string and one for the substring 完整的代码包含两个“ for”循环,一个用于字符串,一个用于子字符串。
To avoid anything other than for loops and a function you could do it like this although I have no idea why. 为了避免除for循环和函数外的其他操作,尽管我不知道为什么,但是可以这样做。 Also you will have to use in
which is pointed out in the comments. 你也将不得不使用in
其中指出了意见。 If a letter in the mainstring matches the first letter in the substring then add it to the temp string t
, then go to the next letters in each and see if they match. 如果主字符串中的一个字母与子字符串中的第一个字母匹配,则将其添加到临时字符串t
,然后转到每个字母中的下一个字母,查看它们是否匹配。 If the temp string equals the substring then it exists and it will return. 如果临时字符串等于子字符串,则它存在并且将返回。
def substring(ss, s):
x = 0
t = ""
for i in range(len(s)):
if s[i] == ss[x]:
t += ss[x]
if t == ss:
return s
x+=1
else:
x = 0
t = ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.