如何使用python搜索列表/数组中的字母? [英] How to search letter in list/array using python?
本文介绍了如何使用python搜索列表/数组中的字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的列表/数组.
I have one list/array like this.
ch = [ eretail, retail, fax, xerox ]
我尝试使用单个/多个字母来提取字符串.
I tried fetch strings using single/multiple letters.
例如,我发送了"e"字母作为输入.如果与字符串匹配,它将搜索整个字符串,该字符串将显示为输出
for example, i sent 'e' letter as input. it will search entire string, incase it will match with string, the string will display as output
示例:
1)Input: e
output: eretail
retail
xerox
2)Input: x
output: fax
xerox
3)Input: o
output: xerox
4)Input: retail
output: eretail
retail
我需要上面的输出.
推荐答案
您可能需要执行以下操作:
You might need to do something like this :
import re
ch = ['eretail', 'retail', 'fax', 'xerox']
input = ['e', 'x', 'o', 'retail']
for each in input:
search = each + '+'
output = []
for i in ch:
if(re.findall(each, i)):
output.append(i)
print('Input', each, '\n', 'output', output)
结果:
Input e
output ['eretail', 'retail', 'xerox']
Input x
output ['fax', 'xerox']
Input o
output ['xerox']
Input retail
output ['eretail', 'retail']
或者,以防万一输入不是数组:
import re
ch = ['eretail', 'retail', 'fax', 'xerox']
input = 'e'
search = input + '+'
output = []
for i in ch:
if(re.findall(search, i)):
output.append(i)
print('Input', input, '\n', 'output', output)
结果:
Input e
output ['eretail', 'retail', 'xerox']
请尝试上面的代码,我是python的初学者-如果需要增强此答案,请编辑此答案. re
也是本示例中使用的python内置的Regex模块.
Please try the above code, I'm a beginner in python - edit this answer if it needs to be enhanced. Also re
is python's built-in Regex module that is being used in this example.
这篇关于如何使用python搜索列表/数组中的字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文