1

I am trying to convert a string into floating point in Python: I have the following Unicode string which I want to convert to 0.02 floating point:

t = (data["streams"][0]["time_base"]) 
print t

And this is the output u'1/50'

I am writing a program which is extracting information from a JSON file and in the future I will need to convert similar strings and I want to automate the process.

6
  • Possible duplicate of How do I convert unicode characters to floats in Python? Commented Feb 3, 2017 at 14:31
  • what can be your unicode strings? apart from 1/50 I mean. Are those always fractions? something else? Commented Feb 3, 2017 at 14:34
  • @Svekke when I try your method I got an error: TypeError: need a single Unicode character as parameter Commented Feb 3, 2017 at 14:36
  • @Jean-FrançoisFabre there are always fractions, actually this is the framerate represented as a fraction so it is always 1/24, 1/25, 1/59.94, 1/60 and so on. Commented Feb 3, 2017 at 14:37
  • @GeorgеStoyanov: And if you use float(u'1/50') ? Commented Feb 3, 2017 at 14:39

1 Answer 1

4

You can split at /, convert to floats, and divide the numbers:

>>> num1, num2 = [float(x) for x in t.split('/')]
>>> num1 / num2
0.02
Sign up to request clarification or add additional context in comments.

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.