Python: Replace integers by floats in string

2k Views Asked by At

I'm looking for a way, to replace every number inside a string by a float number. So I'd turn this: "3/1" to this: "3.0/1.0" Is there a way to do this?

2

There are 2 best solutions below

6
On

You can use re.sub :

>>> s="3/1" 
>>> import re
>>> re.sub(r'(\d+)',r'\1.0',s)
'3.0/1.0'
>>> s="334/14" 
>>> re.sub(r'(\d+)',r'\1.0',s)
'334.0/14.0'
0
On

If they are single strings always in the same format:

s = "3/1"


print("{}.0/{}.0".format(*s.split("/")))