python查找字符串返回_Python:在字符串中查找子字符串并返回子字符串的索引

I have:

a function: def find_str(s, char)

and a string: "Happy Birthday",

I essentially want to input "py" and return 3 but I keep getting 2 to return instead.

Code:

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"))

Not sure what's wrong!

解决方案

Ideally you would use str.find or str.index like demented hedgehog said. But you said you can't ...

Your problem is your code searches only for the first character of your search string which(the first one) is at index 2.

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"))

It produced the following output:

3

8

-1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值