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.

import re

s1 =' 25000 '
s2 = ' 5.5910 '

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 =' 25000 '

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

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

>>> s1 =' 25000 '
>>> s1.replace(" ","")
'25000'
>>> s2 = ' 5.5910 '
>>> s2.replace(" ","")
'5.5910'

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.