执行下列选项的程序,会抛出异常的是()
执行下列选项的程序,会抛出异常的是()
s1 = 'aabbcc'
s2 = 'abc'
count = s1.count(s2)
if count > 0 :
print('s2是s1的子串')
else:
print('s2不是s1的子串')
s1 = 'aabbcc'
s2 = 'abc'
index = s1.index(s2)
if index > -1:
print('s2是s1的子串')
else:
print('s2不是s1的子串')
s1 = 'aabbcc'
s2 = 'abc'
find = s1.find(s2)
if find != -1 :
print('s2是s1的子串')
else:
print('s2不是s1的子串')
s1 = 'aabbcc'
s2 = 'abc'
if s2 in s1:
print('s2是s1的子串')
else:
print('s2不是s1的子串')
分别测试了一下ABCD选项(python 3)
print(s1.count(s2))
运行结果:0
print(s1.index(s2))
运行结果:
ValueError Traceback (most recent call last)
<ipython-input-3-5e3aed89bcc7> in <module>
1 s1 = 'aabbcc'
2 s2 = 'abc'
----> 3 index = s1.index(s2)
4 if index > -1:
5 print('s2是s1的子串')
ValueError: substring not found
print(s1.find(s2))
运行结果:-1
print(s2 in s1)
运行结果:False
字符串型的内置类型index()方法用于找出某个子字符串第一个匹配项的索引位置,如果没有找到则引发ValueError。
count()方法返回子字符串 sub 非重叠出现的次数,没有匹配到对象返回0。
find() 方法类似于index()方法,区别在于没有匹配到对象返回-1。但应该只在你需要知道sub所在位置时使用。 注:要检查 sub 是否为子字符串,请使用 in 操作符。
in 没有匹配到对象返回false。
str.find(str, beg=0, end=len(string)) str.index(str, beg=0, end=len(string))
str.count(str, beg=0, end=len(string))