Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14040

Extract numerical percentage from string containing multiple numbers

$
0
0

I want to extract a numerical percentage in a string. Here are some cases:

  • input: "Bank ABC 123% CDE" -> output: 123.00 (as a float)
  • input: "Some random bank IPCA + 12,34%" -> output: 12.34
  • input: "Bank1 2,3%" -> output: 2.3

Commas are used solely as separators and there's only one percentage for each string, so the following strings will never occur:

  • invalid input: "Bank ABC, 123%"
  • invalid input: "Bank ABC 123% and 12,34%"

Currently, I'm using the following script in Python

def extract_percentage(x: str) -> float:   float((re.sub(r'[^\d,]', '', x)).replace(',','.'))

It works for the first two examples above, but for the third, the output is 12.3

How should I do it? Preferably, using Python.


Viewing all articles
Browse latest Browse all 14040

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>