Steve
Steve

Reputation: 273

Check what number a string ends with in Python

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

Upvotes: 27

Views: 22331

Answers (3)

efotinis
efotinis

Reputation: 14961

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.

 

Upvotes: 36

luizfonseca
luizfonseca

Reputation: 327

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)

Upvotes: -2

Matt Ball
Matt Ball

Reputation: 359826

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.

Upvotes: 15

Related Questions