Reputation: 415
In python, how to extract some char from each item of a list ?
e.g. in a list, each item (modelName) has
cfn99e1195_1.lp
The numbers inside may be different.
I need to get 99 and 1195.
I tried
findN = modelName.find('n')
findE = modelName.find('e')
nodeNum = modelName(findN, findE)
findBar = modelName.find('_')
arcNum = modelName(findE, findBar)
does not work.
thanks
Upvotes: 0
Views: 203
Reputation: 4199
The groupdict could be more illustrative, also a check if the match is really there:
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
OF course, the patter could be reused for all similar matching operations.
Upvotes: 1
Reputation: 9041
This:
nodeNum = modelName(findN, findE)
doesn't make much sense. You're trying to call the string here as if it were a function.
What you want is this:
nodeNum = modelName[findN + 1: findE]
But remember that .find()
can return -1
if the substring wasn't found.
So at the very least, replace .find()
with .index()
which does the same thing but raises an exception instead if the substring is not found.
You might also want to consider using regular expressions to extract the numbers.
Upvotes: 0
Reputation: 18219
consider using regular expressions:
import re
pattern = re.compile(r'^cfn(\d+)e(\d+)')
a, b = pattern.match('cfn99e1195_1.lp').groups()
Upvotes: 1