网站首页 > 基础教程 正文
有的时候,我们需要查找一些内容,输入要查找的文字,能够快速反馈出来。
1 我们先看看in关键字的使用
s = "hello world"
if "world" in s:
print("存在")
else:
print("不存在")
看下运行情况,
说明这个in还是可以的。
2 我们用find方法,
print(s.find("world")) # 输出: 6
print(s.find("python")) # 输出: -1
我们发现find,并不是直接输出来,而是首次出现的索引,没有找到就输出-1
那么我们可以用他查找一些内容的位置。
s2 = "ababaababccccdddddffffabaa"
f_sub = "ab"
start = 0
while True:
pos = s2.find(f_sub, start)
if pos == -1:
break
print(f"找到位置:{pos}")
start = pos + 1 # 继续向后查找,查找的位置更新
运行下
看来还是有用的。
3 有的时候让我们统计一下一个字的次数,用count方法
s = "apple banana apple cherry apple jinritoutiao "
print(s.count("apple")) # 输出: 3
4把找到的字母,统一下大写或者小写,
s4 = "Apple Banana apple Cherry apple Jinritoutiao"
if "jinritoutiao" in s4.lower():
s5=s4.lower()
print(f'忽略大小写存在: {s5}')
我们把代码修改下,输出大写:
s4 = "Apple Banana apple Cherry apple Jinritoutiao"
if "jinritoutiao" in s4.lower():
s5=s4.lower()
print(f'忽略大小写存在: {s5}')
s6= s4.upper()#大写
print(f'忽略大小写存在: {s6}')
说到这里,大家应该多少都了解了些吧。还是老话,看懂了就花点时间练习练习。
猜你喜欢
- 2025-05-25 「Python教程」第6篇 Python基本语法之字符串
- 2025-05-25 失业程序员复习python笔记——字符串
- 2025-05-25 Python字符串分割,你真的会用split()吗?3分钟掌握核心技巧!
- 2025-05-25 不允许你还不会的Python 文件与字符串处理高效技巧
- 2025-05-25 python字符串知识点总结
- 2025-05-25 Python字符串是否有包含子字符串的方法
- 2025-05-25 Python 中 字符串处理的高效方法,不允许你还不知道
- 2025-05-25 Python中,什么是字符串?
- 2025-05-25 Python字符串详解与示例
- 2025-05-25 Python 字符串
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- deletesql (62)
- c++模板 (62)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- console.table (62)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)