0

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
  • Will all strings have the numbers separated by a slash? Commented Jun 13, 2015 at 20:25
  • any type of number (integer, real, complex..) or integers only? Commented Jun 13, 2015 at 21:21

2 Answers 2

4

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'
Sign up to request clarification or add additional context in comments.

6 Comments

But - wait. If I insert a string like "1/30" it does weird things. ("3.00.0") is there another way? - EDIT: Solved. (\d+)
@d0n.key, you must be doing weird things then because you should not get that.
Just solved it, by changing (\d) in the function to (\d+)
@d0n.key if this answered your question, please accept it by clicking on the check mark to turn it green.
If the string contains a decimal number, this will screw things up.
|
2

If they are single strings always in the same format:

s = "3/1"


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.