28

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

1
  • 3
    can the number be negative or have decimal points? Commented Aug 16, 2011 at 22:04

3 Answers 3

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.

 

Sign up to request clarification or add additional context in comments.

Comments

15

I'd use a regular expression, something like /(\d+)$/. This will match and capture one or more digits, anchored at the end of the string.

Read about regular expressions in Python.

3 Comments

+use int to cast the extracted string to an integer.
@Steve, you'd better get into the habit of using raw strings (r'...') for your regular expressions, otherwise you'll soon be entering into a world of pain…
In addition, no need to add parentheses around the match as group(0) or group() returns the whole match anyway.
-2

Oops, correcting (sorry, I missed the point)

you should do something like this ;)

Import the RE module

import re

Then write a regular expression, "searching" for an expression.

s = re.search("[a-zA-Z+](\d{3})$", "string123")

This will return "123" if match or NoneType if not.

s.group(0)

3 Comments

Yep. I couldn't agree more. ;(
Much better :), though your regex is overkill.
Not working for me as it is returning 'g123'. You could use s.group(1) to make it working but you could also make it simpler.

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.