a='1234;5'
print a.index('s')
错误提示为:
> "D:\Python25\pythonw.exe" "D:\zjm_code\kml\a.py"
Traceback (most recent call last):
File "D:\zjm_code\kml\a.py", line 4, in <module>
print a.index('s')
ValueError: substring not found
谢谢
a='1234;5'
print a.index('s')
错误提示为:
> "D:\Python25\pythonw.exe" "D:\zjm_code\kml\a.py"
Traceback (most recent call last):
File "D:\zjm_code\kml\a.py", line 4, in <module>
print a.index('s')
ValueError: substring not found
谢谢
find()
替代-这将告诉您字符串中的位置:a = '1234;5'
index = a.find('s')
if index == -1:
print "Not found."
else:
print "Found at index", index
如果你只想知道这个字符串是否存在,你可以使用in
:
>>> print 's' in a
False
>>> print 's' not in a
True
print ('s' in a) # False
print ('1234' in a) # True
如果你需要索引而不想触发异常,请使用find
。
print a.find('s') # -1
print a.find('1234') # 0
如果您只想检查一个字符串中是否包含子字符串,可以使用in
运算符。
if "s" in mystring:
print "do something"
find()
检查是否为-1(未找到)或使用index()
。str.find()
和 str.index()
几乎是一样的。最大的区别是当字符串没有被找到时,str.index()
会抛出一个错误,就像你得到的那个,而 str.find()
返回 -1,正如其他人已经发表的。
还有两个姐妹方法叫做 str.rfind()
和 str.rindex()
,它们从字符串的末尾开始搜索,并向前工作。
此外,正如其他人已经展示的那样,in
运算符(以及 not in
)也是完全有效的。
最后,如果您想在字符串中查找模式,可以考虑使用正则表达式,尽管我认为太多人在不必要的时候使用它们。用另一些(著名的)话来说,"现在你有了两个问题。"
这就是我现在所拥有的所有信息。然而,如果你正在学习Python和/或编程,我会给我的学生一个非常有用的练习,让他们尝试自己构建Python代码中的*find()
和*index()
,甚至包括in
和not in
(虽然作为函数)。你将获得遍历字符串的良好实践,以及对现有字符串方法的理解。根据下面的说明,让我们尝试这个。
方法1:
if string.find("substring") == -1:
print("found")
else:
print("not found")
方法二:
if "substring" in "string":
print("found")
else:
print("not found")
def substr(s1, s2): # s1='abc' , s2 = 'abcd'
i = 0
cnt = 0
s = ''
while i < len(s2):
if cnt < len(s1):
if s1[cnt] == s2[i]:
cnt += 1
s += s2[i]
else:
cnt = 0
s = ''
i += 1
if s == s1:
print(f'{s1} is substring of {s2}')
else:
print(f'{s1} is not a substring of {s2}')
这是检查一个字符串是否包含另一个子字符串的正确方法。
def sea(str,str1):
if(str1[0:] in str):
return "yes"
else:
return "no"
print(sea("sahil","ah"))