Such as "example123" would be 123, "ex123ample" would be None, and "123example" would be None.
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.
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.
The endswith() method returns True if the string ends with the specified value, otherwise False.
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 stringIn 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With