python 在字符串中查找子字符串
python to find sub string inside string
我是 python 的新手,我对下面的代码有一些简单的问题
代码应该给出结果 'x100' 而它是 'x10' 和 'x100'。如何获得预期的结果。
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
>>>
更简单的方法是
test_list=['x10','x50','x100']
text='this text has x100 only'
for i in test_list:
if i in text.split():
print "found "+i
检测
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()
您可以使用 .split()
来查找它是否在单词列表中:
>>> 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
您可以使用这个简单的列表理解来查找所有实例。奖励:它只计算一次拆分。
def f(s, lst):
return [item for item in lst if item in s.split()]
测试一下:
>>> test_list=['x10','x50','x100']
>>> text='this text has x100 only'
>>> f(text, test_list)
['x100']
我是 python 的新手,我对下面的代码有一些简单的问题 代码应该给出结果 'x100' 而它是 'x10' 和 'x100'。如何获得预期的结果。
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
>>>
更简单的方法是
test_list=['x10','x50','x100']
text='this text has x100 only'
for i in test_list:
if i in text.split():
print "found "+i
检测
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()
您可以使用 .split()
来查找它是否在单词列表中:
>>> 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
您可以使用这个简单的列表理解来查找所有实例。奖励:它只计算一次拆分。
def f(s, lst):
return [item for item in lst if item in s.split()]
测试一下:
>>> test_list=['x10','x50','x100']
>>> text='this text has x100 only'
>>> f(text, test_list)
['x100']