专业编程基础技术教程

网站首页 > 基础教程 正文

Python中如何查找字符串及快速掌握一些运用

ccvgpt 2025-05-25 11:13:32 基础教程 2 ℃

有的时候,我们需要查找一些内容,输入要查找的文字,能够快速反馈出来。

1 我们先看看in关键字的使用

Python中如何查找字符串及快速掌握一些运用

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}')

说到这里,大家应该多少都了解了些吧。还是老话,看懂了就花点时间练习练习。

最近发表
标签列表