添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
精选内容/技术社群/优惠产品, 尽在小程序
立即前往

如何在Python中获取List中字符串值内的特定字符串

在Python中,可以使用字符串的内置方法和正则表达式来获取List中字符串值内的特定字符串。

方法一:使用字符串的内置方法 可以使用字符串的 split() 方法将字符串拆分成一个列表,然后遍历列表,判断特定字符串是否在列表中的每个元素中。

代码语言: txt
复制
my_list = ['apple is a fruit', 'banana is a fruit', 'orange is a fruit']
specific_string = 'fruit'
result = []
for string in my_list:
    if specific_string in string:
        result.append(string)
print(result)

输出:

代码语言: txt
复制
['apple is a fruit', 'banana is a fruit', 'orange is a fruit']

方法二:使用正则表达式 可以使用Python的 re 模块来使用正则表达式匹配特定字符串。

代码语言: txt
复制
import re
my_list = ['apple is a fruit', 'banana is a fruit', 'orange is a fruit']