在python中,如何从列表的每个项目中提取一些字符?
在python中,如何从列表的每个项目中提取一些字符 e、 g.在列表中,每个项目(modelName)都有 里面的数字可能不同 我需要得到99和1195 我试过了在python中,如何从列表的每个项目中提取一些字符?,python,list,Python,List,在python中,如何从列表的每个项目中提取一些字符 e、 g.在列表中,每个项目(modelName)都有 里面的数字可能不同 我需要得到99和1195 我试过了 findN = modelName.find('n') findE = modelName.find('e') nodeNum = modelName(findN, findE) findBar = modelName.find('_') arcNum = modelName(findE, findBar)
findN = modelName.find('n')
findE = modelName.find('e')
nodeNum = modelName(findN, findE)
findBar = modelName.find('_')
arcNum = modelName(findE, findBar)
不起作用
谢谢考虑使用正则表达式:
import re
pattern = re.compile(r'^cfn(\d+)e(\d+)')
a, b = pattern.match('cfn99e1195_1.lp').groups()
这:
没什么意义。您试图在这里调用字符串,就好像它是一个函数一样
你想要的是:
nodeNum = modelName[findN + 1: findE]
但是请记住,如果未找到子字符串,则.find()
可以返回-1
因此,至少,将.find()
替换为.index()
,这会执行相同的操作,但如果未找到子字符串,则会引发异常
您可能还想考虑使用正则表达式来提取数字。
< P>该组可以更具说明性,也可以检查匹配是否真的存在:pattern = re.compile(r'^cfn(?P<a>\d+)e(?P<b>\d+)')
m = pattern.match('cfn99e1195_1.lp')
d = {}
if m:
d = m.groupdict()
# the result will be in the form {'a': '99', 'b': '1195'}
# or {} if not matched
pattern=re.compile(r'^cfn(?P\d+)e(?P\d+)
m=模式匹配('cfn99e1195_1.lp'))
d={}
如果m:
d=m.groupdict()
#结果的形式为{'a':'99','b':'1195'}
#或{}如果不匹配
当然,模式可以用于所有类似的匹配操作。modelName=array[0],a,b=pattern.match(modelName).groups(),我得到错误:AttributeError:“NoneType”对象没有属性“groups”,这意味着模式无法与字符串匹配。什么是数组[0]?对于glob.glob中的infle(os.path.join(path,'cfne_1.lp_obj_node_arc.txt'):print“当前文件是:”+infle array=[]对于infle中的行:#array.append(line)array=line.split()breakarray[0]是从line.split()中获取的,行是从文件中读取的。我的意思是数组[0]的内容。您能打印数组[0]来告诉我字符串是什么吗?对不起,前面的模棱两可。
nodeNum = modelName[findN + 1: findE]
pattern = re.compile(r'^cfn(?P<a>\d+)e(?P<b>\d+)')
m = pattern.match('cfn99e1195_1.lp')
d = {}
if m:
d = m.groupdict()
# the result will be in the form {'a': '99', 'b': '1195'}
# or {} if not matched