python extract the price from a string

Solutions on MaxInterview for python extract the price from a string by the best coders in the world

showing results for - "python extract the price from a string"
Nicola
07 May 2020
1# Visit: https://regexr.com/
2# and look at the Menu/Cheatsheet
3
4# Extract the price from a string
5price = 'Price is: $520,130.250'
6expr = 'Price is: \$([0-9,]*\.[0-9]*)'
7
8match = re.search(expr, price)
9print(match.group(0))              # give entire match
10print(match.group(1))              # give only text in brackets
11
12price_without_comma = match.group(1).replace(',', '')     # replace comma because can't be converted to a number
13price_num = float(price_without_comma)                    # convert string to float 
14print(price_num)