Python Practice › RegEx Programs › Program 18

Extract prices

EasyRegEx Programs · 18 of 20

Write a Python program to extract rupee prices like Rs 1,499.50 and add them up.

Advertisement
Output
[349.0, 1499.5, 99.0] 1947.5

Approach

  1. Capture the number, remove commas, convert.

Solution

Python
import re text = "Mouse Rs 349, keyboard Rs 1,499.50, cable Rs 99"prices = [float(p.replace(",", "")) for p in re.findall(r"Rs\s?([\d,]+(?:\.\d+)?)", text)]print(prices, sum(prices))
Output
[349.0, 1499.5, 99.0] 1947.5
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs