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?
-
Will all strings have the numbers separated by a slash?user4938328– user49383282015-06-13 20:25:08 +00:00Commented Jun 13, 2015 at 20:25
-
any type of number (integer, real, complex..) or integers only?Pynchia– Pynchia2015-06-13 21:21:11 +00:00Commented Jun 13, 2015 at 21:21
Add a comment
|
2 Answers
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'
6 Comments
d0n.key
But - wait. If I insert a string like "1/30" it does weird things. ("3.00.0") is there another way? - EDIT: Solved. (\d+)
Padraic Cunningham
@d0n.key, you must be doing weird things then because you should not get that.
d0n.key
Just solved it, by changing (\d) in the function to (\d+)
Malik Brahimi
If the string contains a decimal number, this will screw things up.
|