How can I find the last number in any big string?
For eg in the following string I want 47 as the output:
'tr bgcolor="aa77bb"td>font face="verdana"color="white" size="2">b>Total/b>/font>/td>\td>font face="verdana"color="white" size="2">b>47/b>/font>/td>/tr>'
PS: We don't know the number. The number 47 is just an example. It can be any number from 0 to 900.
The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found. The rfind() method is almost the same as the rindex() method. See example below.
To access the last n characters of a string in Python, we can use the subscript syntax [ ] by passing -n: as an argument to it. -n is the number of characters we need to extract from the end position of a string.
This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.
>>> import re
>>> text = 'tr bgcolor="aa77bb"td>font face="verdana"color="white" size="2">b>Total/b>/font>/td>\td>font face="verdana"color="white" size="2">b>47/b>/font>/td>/tr>'
>>> re.findall(r'\d+', text)[-1]
'47'
If you need to match floating points there's always this
For very long strings this is more efficient:
re.search(r'\d+', text[::-1]).group()[::-1]
I guess I don't know enough about the implementation details / performance of finding a bunch of results and choosing the last, vs just finding the last to begin with (didn't do any performance comparisons); but, this very well might be faster:
>>> text = 'tr bgcolor="aa77bb"td>font face="verdana"color="white" size="2">b>Total/b>/font>/td>\td>font face="verdana"color="white" size="2">b>47/b>/font>/td>/tr>'
>>> import re
>>> re.search(r'(\d+)\D+$', text).group(1)
'47'
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