问题描述
我有:
一个函数:
def find_str(s, char)
和一个字符串:"Happy Birthday"
,
我本质上想输入 "py"
并返回 3
但我一直让 2
返回.
I essentially want to input "py"
and return 3
but I keep getting 2
to return instead.
代码:
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"))
不知道怎么了!
推荐答案
理想情况下,您应该使用 str.find 或 str.index 就像疯了的刺猬说的.但你说你不能...
Ideally you would use str.find or str.index like demented hedgehog said. But you said you can't ...
您的问题是您的代码仅搜索搜索字符串的第一个字符(第一个字符)位于索引 2 处.
Your problem is your code searches only for the first character of your search string which(the first one) is at index 2.
你基本上是说如果 char[0]
在 s
中,增加 index
直到 ch == char[0]
在我测试时返回 3 但它仍然是错误的.这是一种方法.
You are basically saying if char[0]
is in s
, increment index
until ch == char[0]
which returned 3 when I tested it but it was still wrong. Here's a way to do it.
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"))
它产生了以下输出:
3
8
-1
这篇关于Python:在字符串中查找子串并返回子串的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!