Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 Finding the last number in a string

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.

like image 586
Mihir Kulkarni Avatar asked Jun 09 '13 07:06

Mihir Kulkarni


People also ask

How do you find the last number in a string in Python?

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.

How do you find the last three digits of a string in Python?

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.

How do you find a number in a string in Python?

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.


2 Answers

>>> 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]
like image 195
jamylak Avatar answered Nov 06 '22 06:11

jamylak


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'
like image 28
Matt Anderson Avatar answered Nov 06 '22 08:11

Matt Anderson