首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python在字符串中查找子字符串

python在字符串中查找子字符串
EN

Stack Overflow用户
提问于 2015-01-14 13:43:27
回答 3查看 96关注 0票数 0

我对python还不熟悉,在代码下面的代码中,我遇到了简单的问题,代码应该给出结果'x100‘,而它是'x10’和‘x100’,如何得到预期的结果。

代码语言:javascript
复制
test_list=['x10','x50','x100']
text='this text has x100 only'
for i in test_list:
    if  text.find(i)!=-1:
        print "found "+i 
>>> 
found x10
found x100
>>> 
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-01-14 13:44:58

更简单的方法是

代码语言:javascript
复制
test_list=['x10','x50','x100']
text='this text has x100 only'
for i in test_list:
    if  i in text.split():
        print "found "+i 

探测

代码语言:javascript
复制
test_list=['x10','x50','x100']
test_list= sorted(test_list,key = lambda x: len(x), reverse = True)
text='this text has x100n only'
import re
a = re.search("|".join(test_list),text)
if a:
    print "Found",a.group()
票数 1
EN

Stack Overflow用户

发布于 2015-01-14 13:45:14

您可以使用.split()来查找它是否在单词列表中:

代码语言:javascript
复制
>>> test_list=['x10','x50','x100']
>>> text='this text has x100 only'
>>> for i in test_list:
...   if i in text.split():
...     print "found",i
...
found x100
票数 1
EN

Stack Overflow用户

发布于 2015-01-14 14:04:52

您可以使用这个简单的列表理解来查找所有实例。奖励:它只计算一次分割。

代码语言:javascript
复制
def f(s, lst):
    return [item for item in lst if item in s.split()]  

测试它:

代码语言:javascript
复制
>>> test_list=['x10','x50','x100']
>>> text='this text has x100 only'
>>> f(text, test_list)
['x100']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27944387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档