Alex Rivera | Logout

Check what number a string ends with in Python

Asked 2011-08-16T21:51:37.643
28

Such as "example123" would be 123, "ex123ample" would be None, and "123example" would be None.

Edit
Report

1 Answer

37

You can use regular expressions from the re module:

import re
def get_trailing_number(s):
    m = re.search(r'\d+$', s)
    return int(m.group()) if m else None

The r'\d+$' string specifies the expression to be matched and consists of these special symbols:

  • \d: a digit (0-9)
  • +: one or more of the previous item (i.e. \d)
  • $: the end of the input string

In other words, it tries to find one or more digits at the end of a string. The search() function returns a Match object containing various information about the match or None if it couldn't match what was requested. The group() method, for example, returns the whole substring that matched the regular expression (in this case, some digits).

The ternary if at the last line returns either the matched digits converted to a number or None, depending on whether the Match object is None or not.

 

answered 2011-08-16T22:13:15.750

Your Answer