``````s1 ='999'
s2 = '99.99'

mypat = re.compile('(^([0-9]+[.]+[0-9]+)|([0-9])\$)')
rate= mypat.search(s1)
print rate.group()

>>> print rate.groups()
('9', None, '9')
>>> rate=mypat.search(s2)
>>> print rate.group()
99.99``````

I need to get price = float(rate.group()). Price=999 or Price=99.99.
I think there is a problem when s1='999', when I do this:

``````>>> rate = mypat.search(s1)
>>> price = float(rate.group())
>>> print price
9.0``````

I only get 9.0, I need to get 999.0. I think my way of doing rate.group() is wrong, can someone help me so I can get 999.0.

2
Contributors
2
Replies
3
Views
10 Years
Discussion Span
Last Post by ghostdog74
``````import re

s1 ='&nbsp;25000&nbsp;'
s2 = '&nbsp;5.5910&nbsp;'

mypat = re.compile('[0-9]*(\.[0-9]*|\$)')
rate= mypat.search(s1)
print rate.group()

rate=mypat.search(s2)
print rate.group()
rate = mypat.search(s1)
price = float(rate.group())
print price``````

I get an error when it hits the whole number, that is in this format: s1 ='&nbsp;25000&nbsp;'

price = float(rate.group())
ValueError: empty string for float()

why do you think that regular expression is the way to go?

``````>>> s1 ='&nbsp;25000&nbsp;'
>>> s1.replace("&nbsp;","")
'25000'
>>> s2 = '&nbsp;5.5910&nbsp;'
>>> s2.replace("&nbsp;","")
'5.5910'``````

regular expressions will be the last in mind for solving string problems in Python, unless really desperate

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.