Reputation: 362
How can I parse a string ['FED590498']
in python, so than I can get all numeric values 590498
and chars FED
separately.
Some Samples:
['ICIC889150']
['FED889150']
['MFL541606']
and [ ] is not part of string...
Upvotes: 0
Views: 112
Reputation: 17649
Given the requirement that there are always 3 or 4 letters you can use:
import re
characters, numbers = re.findall(r'([A-Z]{3,4})(\d+)', 'FED590498')[0]
characters, numbers
#('FED', '590498')
Or even:
ids = ['ICIC889150', 'FED889150', 'MFL541606']
[re.search(r'([A-Z]{3,4})(\d+)', id).groups() for id in ids]
#[('ICIC', '889150'), ('FED', '889150'), ('MFL', '541606')]
As suggested by Martjin, search
is the preferred way.
Upvotes: 1
Reputation: 1124488
If the number of letters is variable, it's easiest to use a regular expression:
import re
characters, numbers = re.search(r'([A-Z]+)(\d+)', inputstring).groups()
This assumes that:
You can lock the pattern down further by using {3, 4}
instead of +
to limit repetition to just 3 or 4 instead of at least 1, etc.
Demo:
>>> import re
>>> inputstring = 'FED590498'
>>> characters, numbers = re.search(r'([A-Z]+)(\d+)', inputstring).groups()
>>> characters
'FED'
>>> numbers
'590498'
Upvotes: 5