0

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...

3
  • 2
    And what is the pattern here? Is there always 3 characters, then numbers? Is there a mix? Are the [, ] brackets part of the string, are the quotes? Commented Mar 18, 2014 at 11:48
  • 3 or 4 character then numbers... Commented Mar 18, 2014 at 11:49
  • If you can give us multiple input samples and expected output for each we can actually help you here. Commented Mar 18, 2014 at 11:49

2 Answers 2

5

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:

  • The letters are uppercase ASCII
  • There is at least 1 character, and 1 digit in each input string.

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'
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Martijn Pieters
Out of curiosity, is it more idiomatic to use re.search in combination with groups or re.findall with [0]?
@Matt: I'd use re.search() here if it is an error for there to be more than one such pattern in the input string.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.