Search code examples
pythonstring-parsing

Parsing String with Python


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


Solution

  • 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'