首页 > 试题广场 >

执行下列选项的程序,会抛出异常的是()

[单选题]

执行下列选项的程序,会抛出异常的是()

  • 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的子串')

count()函数没有匹配到对象返回0
index()函数没有匹配到对象报错value Error
find()函数没有匹配到对象返回-1
in 没有匹配到对象返回false
发表于 2022-03-03 15:36:50 回复(3)

分别测试了一下ABCD选项(python 3)

A count()返回出现的次数

print(s1.count(s2))

运行结果:0

B index()返回首次出现s2的索引位置,如果没找到则报异常

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

C find()返回首次出现s2的位置,如果没找到则返回-1

print(s1.find(s2))

运行结果:-1

D 返回 s2 in s1 的真假

print(s2 in s1)

运行结果:False

发表于 2022-01-08 11:16:18 回复(1)
index()函数用于找出某个值第一个匹配项的索引位置,如果没有找到对象则抛出异常。 
发表于 2021-12-20 14:52:56 回复(1)

字符串型的内置类型index()方法用于找出某个子字符串第一个匹配项的索引位置,如果没有找到则引发ValueError

count()方法返回子字符串 sub 非重叠出现的次数,没有匹配到对象返回0。

find() 方法类似于index()方法,区别在于没有匹配到对象返回-1。但应该只在你需要知道sub所在位置时使用。 注:要检查 sub 是否为子字符串,请使用 in 操作符。

in 没有匹配到对象返回false。

编辑于 2022-03-11 20:34:52 回复(0)
count()函数没有匹配到对象返回0
index()函数没有匹配到对象报错value Error
find()函数没有匹配到对象返回-1
in 没有匹配到对象返回false
发表于 2022-04-03 22:46:28 回复(0)
find 作为变量不会报错
发表于 2022-06-28 14:46:40 回复(0)
count()函数没有匹配到对象返回0 index()函数没有匹配到对象报错value Error find()函数没有匹配到对象返回-1 in 没有匹配到对象返回false
发表于 2022-03-28 23:21:23 回复(0)
1. find(), index()用法一样:
str.find(str, beg=0, end=len(string)) str.index(str, beg=0, end=len(string))
查询的子字符串,起始位置,结束位置;起始和结束位置指定了查找范围。
如果子字符串存在查找范围中,返回匹配的子字符串第一个值的索引值如果不在:find()返回-1, index()抛出异常ValueError 。
2. count() 用法
str.count(str, beg=0, end=len(string))
用于统计字符串里某个字符或子字符串出现的次数, 如果没有指定子字符串返回0.
发表于 2022-03-02 17:19:29 回复(0)
str未匹配到时返回-1
发表于 2022-08-03 21:40:42 回复(0)
count()函数返回查找到匹配对象的个数,没有找到匹配对象返回0;
index()函数返回找到匹配对象的索引位置,没有找到对象抛出异常;
find()函数返回首次出现匹配对象胡索引位置,没有找到对象返回-1;
in()函数找到匹配对象返回true,没找到返回false;
综合上述,答案为B。
发表于 2022-07-20 09:46:12 回复(0)
Index方法用于找出某个子字符串第一个匹配项的索引位置,如果没有找到,则报错 Count方法用于统计所匹配字符串的个数,没有匹配到,则返回0 Find方法用于查找是否有包含的子串,没有则返回-1
发表于 2023-04-28 18:47:56 回复(0)

发表于 2023-01-25 22:01:11 回复(0)
啧,老是记不住
count()函数没有匹配到对象返回0
index()函数没有匹配到对象报错value Error
find()函数没有匹配到对象返回-1
in 没有匹配到对象返回false
发表于 2022-11-01 15:59:42 回复(0)
只能匹配2个,当s2=ab,就能匹配到。想请问下为什么?
发表于 2022-05-14 15:34:10 回复(0)
本题主要考察index()、find()、count()的方法
index是将s2 在s1首次出现的字符所对应的索引值
find是将s2在s1首次出现的位置,返回的索引值
count指的是s2在s1中出现的次数,例如:s1 = 'hellopython' s2='py' s2字符串在s1字符串出现的次数为1次
发表于 2022-04-27 10:55:44 回复(0)
直接看字符串的方法(属性),秒选即可,一切皆对象
发表于 2022-04-21 08:42:29 回复(0)
index找出指定字符串,如果没有就报错
发表于 2022-03-23 14:16:12 回复(0)