Tyl*_*ler 51 python string indexing substring
我有:
功能: def find_str(s, char)
和一个字符串:"Happy Birthday",
我本质上想输入"py"并返回,3但我不断2返回.
码:
def find_str(s, char):
index = 0
if char in s:
char = char[0]
for ch in s:
if ch in s:
index += 1
if ch == char:
return index
else:
return -1
print(find_str("Happy birthday", "py"))
Run Code Online (Sandbox Code Playgroud)
不确定是什么问题!
dem*_*hog 179
你知道在python中有一个内置的字符串对象方法吗?
s = "Happy Birthday"
s2 = "py"
print s.find(s2)
Run Code Online (Sandbox Code Playgroud)
Python是一种"电池包含的语言",其编写的代码可以完成你想要的大部分(无论你想要什么)..除非这是作业:)
编辑:find如果找不到字符串,则返回-1.
Eri*_*tin 15
理想情况下你会使用str.find或str.index这样的痴呆hedgehog说.但是你说你不能......
您的问题是您的代码仅搜索搜索字符串的第一个字符(第一个字符)位于索引2处.
你基本上是说,如果char[0]是s,增量index直到ch == char[0]这时候我测试了它,但它仍然是错误的返回3.这是一种方法.
def find_str(s, char):
index = 0
if char in s:
c = char[0]
for ch in s:
if ch == c:
if s[index:index+len(char)] == char:
return index
index += 1
return -1
print(find_str("Happy birthday", "py"))
print(find_str("Happy birthday", "rth"))
print(find_str("Happy birthday", "rh"))
Run Code Online (Sandbox Code Playgroud)
它产生了以下输出:
3
8
-1
Run Code Online (Sandbox Code Playgroud)
正则表达式中还有另一种选择,search方法
import re
string = 'Happy Birthday'
pattern = 'py'
print(re.search(pattern, string).span()) ## this prints starting and end indices
print(re.search(pattern, string).span()[0]) ## this does what you wanted
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果你想找到一个模式的所有出现,而不仅仅是第一个,你可以使用finditer 方法
import re
string = 'i think that that that that student wrote there is not that right'
pattern = 'that'
print([match.start() for match in re.finditer(pattern, string)])
Run Code Online (Sandbox Code Playgroud)
这将打印匹配的所有起始位置。