Such as "example123" would be 123, "ex123ample" would be None, and "123example" would be None.
3 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.
Comments
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
int to cast the extracted string to an integer.r'...') for your regular expressions, otherwise you'll soon be entering into a world of pain…group(0) or group() returns the whole match anyway.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
'g123'. You could use s.group(1) to make it working but you could also make it simpler.