Python: How to extract decimal value out of a string, when a specific letter equals the decimal place? Example SG0P01, I want to make 0.01

Viewed 66

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?

5 Answers

With regex:

import re

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

demo

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

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

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)

If you know that the prefix will always be SG (or any two-character sequence), you can do this:

dec = string[2:].replace("P",".")

If the prefix can be of arbitrary length and you know you that the decimal proxy P will always have at least one digit before and after, you can do this:

import re
dec = re.search(r'\d+P\d+', string)[0].replace("P",".")

Explanation:

  • the regex pattern r'\d+P\d+' matches one or more digits followed by P followed by one or more digits
  • search() returns a match object and using [0] gets the 0'th group in the match object, which is 0P01 in your example
  • replace returns a string with all occurrences of P replaced by ., which is 0.01 in your example.
Related