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

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

成员操作符 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开始)
相关文章
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
335 100
|
3月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
453 99
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
3月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
3月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
3月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
4月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
350 0
|
4月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
295 92
|
4月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。

推荐镜像

更多