Posts Tagged ‘Strings’

HowTo: Extract numeric suffix from a string in Python

I recently needed to extract a numeric suffix from a string value in Python. Initially I did the following:

import re

def extractNumSuffix(value):

    return (None if (‘^\D*(\d+)$’, value, re.IGNORECASE)) is None else

Note that return has a single-line expression.



prints 1030

Tried it online at:


However, then I found out that Assignment Expressions in Python only work from Python 3.8 and up, so I changed it to this one:

import re

def extractNumSuffix(value):"^\D*(\d+)$", value, re.IGNORECASE)
    return (None if search is None else

which should work in Python 2.x too. Don’t forget to import the regular expressions (re) module.

%d bloggers like this: