龙空技术网

python经典案例:查找字符串

菜就多练呀 298

前言:

目前同学们对“python if string”大概比较重视,小伙伴们都需要知道一些“python if string”的相关内容。那么小编也在网上收集了一些有关“python if string””的相关内容,希望各位老铁们能喜欢,你们快快来了解一下吧!

问题:查找字符串

1.使用in关键字查找字符串

#!/usr/bin/python#coding:utf-8#author:菜就多练呀text = "Hello, welcome to my world."search_string = "welcome"if search_string in text:    print("找到字符串!")#找到字符串!else:    print("未找到字符串!")

2.使用字符串的find()方法

#!/usr/bin/python#coding:utf-8#author:菜就多练呀text = "Hello, welcome to my world."search_string = "welcome"position = text.find(search_string)if position != -1:    print("找到字符串!")    print("位置:", position)else:    print("未找到字符串!")

输出结果:

找到字符串!位置: 7

3.使用正则表达式

#!/usr/bin/python#coding:utf-8#author:菜就多练呀import retext = "Hello, welcome to my world."search_string = "welcome"pattern = re.compile(search_string)if pattern.search(text):    print("找到字符串!")#找到字符串!else:    print("未找到字符串!")

4.使用count()方法查找字符串

#!/usr/bin/python#coding:utf-8#author:菜就多练呀text = "Hello, welcome to my world. Welcome to our world."search_string = "welcome"count = text.count(search_string)print("字符串 'welcome' 出现的次数:", count)#字符串 'welcome' 出现的次数: 1

5.使用 split() 方法查找字符串

#author:菜就多练呀text = "Hello, welcome to my world."search_string = "welcome"words = text.split()for word in words:    if word == search_string:        print("找到字符串!")        breakelse:    print("未找到字符串!")

注意:使用split()方法,一定要注意标点符号。如果查找world时,结果为未找到字符串。因为split()方法的结果为:['Hello,', 'welcome', 'to', 'my', 'world.']

如果想去掉标点符号,可以使用下面方法:

def remove_punctuation(word):    return word.replace(",", "").replace("!", "").replace("?", "")my_list = ["Hello,", "welcome", "to", "my", "world!"]no_punctuation_list = [remove_punctuation(word) for word in my_list]print(no_punctuation_list)

输出结果:

['Hello', 'welcome', 'to', 'my', 'world']

标签: #python if string #python文件查找字符串 #python查找替换word字符串