2020-09-03

tech2022-10-01  69

Python判断一个字符串是否包含某个指定的字符串

转载自:https://www.cnblogs.com/poloyy/p/12207464.html

成员操作符 in 

1 str = "string test string test" 2 find1 = "str" 3 find2 = "test" 4 print(find1 in str) # True 5 print(find1 not in str) # False

偷偷说一句:in不只是在字符串中可以使用哦!期待后面的教程叭

 

使用字符串对象的 find() 、 rfind() 、 index() 、 rindex() 

1 str = "string test string test" 2 find1 = "str" 3 find2 = "test" 4 # find 5 print(str.find(find1))  # 0 6 print(str.find(find2))  # 7 7 8 # rfind 9 print(str.rfind(find1))  # 12 10 print(str.rfind(find2))  # 19 11 12 # index 13 print(str.index(find1))  # 0 14 print(str.index(find2))  # 7 15 16 # rindex 17 print(str.rindex(find1))  # 12 18 print(str.rindex(find2))  # 19 19 20 # count 21 print(str.count(find1))  # 2 22 print(str.count(find2))  # 2

 

find()和index()的区别

方法区别 find() 获取值时,如果要查找的值不存在,会返回-1 index() 获取值的索引时,如果不存在值,会报错

 

find()和rfind()的区别

方法区别 find()从字符串左边开始查询子字符串匹配到的第一个索引(从0开始) rfind() 从字符串右边开始查询字符串匹配到的第一个索引(从0开始)

 

index()和rindex()的区别

方法区别 index() 从字符串左边开始查询子字符串匹配到的第一个索引(从0开始) rindex() 从字符串右边开始查询字符串匹配到的第一个索引(从0开始)
最新回复(0)