我有:
功能:
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"))
不知道出了什么问题!
字符串对象有一个内置方法 find。
s = "Happy Birthday"
s2 = "py"
print(s.find(s2))
Python 是一种“自带电池的语言”,编写的代码可以完成您想要的大部分操作(无论您想要什么)..除非这是家庭作业:)
如果找不到字符串,find
返回-1。
理想情况下,您会像疯狂刺猬所说的那样使用str.find或str.index。但你说你不能...
您的问题是您的代码仅搜索搜索字符串的第一个字符(第一个字符)位于索引 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"))
它产生了以下输出:
3
8
-1
正则表达式还有另一种选择,
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
顺便说一句,如果您想查找某个模式的所有出现次数,而不仅仅是第一个,您可以使用
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)])
这将打印比赛的所有起始位置。
添加@demented刺猬关于使用
find()
的答案
在效率
方面在调用
find()
之前,可能值得首先检查 s1 是否在 s2 中。因为
in
运算符非常高效
s1 in s2
转换效率更高:
index = s2.find(s1)
到
index = -1
if s1 in s2:
index = s2.find(s1)
这对于当
find()
经常返回 -1 时很有用。
我发现它的速度要快得多,因为
find()
在我的算法中被多次调用,所以我认为值得一提
这是一个简单的方法:
my_string = 'abcdefg'
print(text.find('def'))
输出:
3
如果子串不存在,你会得到-1。 例如:
my_string = 'abcdefg'
print(text.find('xyz'))
输出:
-1
有时,如果子字符串不存在,您可能想抛出异常:
my_string = 'abcdefg'
print(text.index('xyz')) # It returns an index only if it's present
输出:
回溯(最近一次调用最后一次):
文件“test.py”,第 6 行,位于 打印(text.index('xyz'))
值错误:找不到子字符串
参加聚会晚了,正在寻找相同的内容,因为“in”无效,我刚刚创建了以下内容。
def find_str(full, sub):
index = 0
sub_index = 0
position = -1
for ch_i,ch_f in enumerate(full) :
if ch_f.lower() != sub[sub_index].lower():
position = -1
sub_index = 0
if ch_f.lower() == sub[sub_index].lower():
if sub_index == 0 :
position = ch_i
if (len(sub) - 1) <= sub_index :
break
else:
sub_index += 1
return position
print(find_str("Happy birthday", "py"))
print(find_str("Happy birthday", "rth"))
print(find_str("Happy birthday", "rh"))
产生
3
8
-1
删除 lower(),以防不需要不区分大小写的查找。
没有直接回答这个问题,但我最近遇到了一个类似的问题,要求我计算给定字符串中子字符串重复的次数。这是我写的函数:
def count_substring(string, sub_string):
cnt = 0
len_ss = len(sub_string)
for i in range(len(string) - len_ss + 1):
if string[i:i+len_ss] == sub_string:
cnt += 1
return cnt
find() 函数可能只返回第一个出现的索引。存储索引而不是仅仅计数,可以为我们提供子字符串在字符串中重复的不同索引集。
免责声明:我对 Python 编程“极其”陌生。