Home > Back-end >  Python: How to extract decimal value out of a string, when a specific letter equals the decimal plac
Python: How to extract decimal value out of a string, when a specific letter equals the decimal plac

Time:04-01

I have a string SG0P01, and I want to convert it to a decimal 0.01, the P is the decimal place. I am not sure how to do this. I have tried using .replace, re, etc but cant figure it out.

string = SG0P01
dec = (string.replace("P","."))

This results in SG0.01, now I just need to get rid of the SG, I tried using (re.sub('\D','',dec)) but that removes the decimal as well. Is there a way to preserve the decimal, or just do this entire thing in a better way?

CodePudding user response:

With regex:

import re

x = "SG0P01"
print(float(re.sub(r"SG\dP", "", x))/100)
0.01

demo

CodePudding user response:

One way to convert it to string is iterate over individual characters, check them if they are digits or . and join them:

s = "SG0P01"

s = "".join(ch for ch in s.replace("P", ".") if ch.isdigit() or ch == ".")
print(float(s))

Prints:

0.01

CodePudding user response:

I would extract the string with the decimal first and then replace the P. After that the correct string can be converted to a float:

import re

string = 'SG0P01'
number = float(re.search('\d P\d ', string)[0].replace("P","."))
print(number)

Output:

0.01

CodePudding user response:

With a regex rule such as SG0P(\d ) you target the digits after the term SG0P and add a . in front of it, for the cast to float.

import re
s = 'SG0P01'

s = re.sub(r'SG0P(\d )', r'.\1', s)
s = float(s)
print(s)
  • Related