Python。如何编写一个函数来查找字符串中第一次出现子字符串的位置?
问题描述:
我需要写一个返回Python中的字符串中的第一子串的位置,而无需使用string.find(sub)
Python。如何编写一个函数来查找字符串中第一次出现子字符串的位置?
def sublocation(string,sub):
i=0
while i<len(string):
o=0
while o<len(sub):
u=i
if string[i] == sub[o]:
o=o+1
u=u+1
result=True
i=len(string)
else:
i=i+1-u
result=False
答
我尝试这样做:
myString = "Hellow World!"
index = str.find(myString, "World")
print(index)
输出功率为:
>>>
7
>>>
这是你想要的吗?
答
我想这可能会帮助你学习如何在Python中循环。如果子字符串是分开的,您可以使用.split()将其分割成可以本机迭代的子字符串列表。 '枚举'枚举甚至给你索引。
def sub_search_location(inp_str,sub_string):
for pos, sub in enumerate(inp_str.split(' ')):
if sub_string == sub:
return pos
else:
return False
>>> sub_search_location("this is the string for finding sub string", "string")
3
然而,这仅适用于子串没有空间
>>> sub_search_location("this is the string for finding sub string", "sub string")
False
当然你也可以使用str.find
正如其他人推荐的,但看你的代码,我认为你必须学会更重要的事情而不仅仅是对任意方法的调用。
答
你可以使用内置函数find,em,“Hello world”.find(“world”)将返回6.函数索引也可以这样做,但是当字符串没有子串你搜索。
答
尝试使用.find()方法。它将返回您正在尝试查找的子字符串的索引。
使用'str.index'。我会帮你的。 – 2014-11-04 09:16:12
到目前为止您尝试过了什么,为什么您需要自己编写而不是使用现有的Python函数? – nos 2014-11-04 09:17:03
欢迎来到SO,这可能会帮助你http://stackoverflow.com/help/how-to-ask – greole 2014-11-04 09:17:51