Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check what number a string ends with in Python

Tags:

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

like image 475
Steve Avatar asked Aug 16 '11 21:08

Steve


People also ask

How do you check if a string ends with a digit in Python?

Python string method endswith() returns True if the string ends with the specified suffix, otherwise return False optionally restricting the matching with the given indices start and end.

How do you check if a string ends with a number?

To check if a string ends with a number, call the test() method on a regular expression that matches one or more numbers at the end a string. The test method returns true if the regular expression is matched in the string and false otherwise.

What does Endswith () do in Python?

The endswith() method returns True if the string ends with the specified value, otherwise False.


1 Answers

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.

 

like image 112
efotinis Avatar answered Sep 17 '22 03:09

efotinis