简体   繁体   English

在Python中将字符串转换为浮点数

[英]Convert string into floating point in Python

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: 我正在尝试将字符串转换为Python中的浮点数:我有以下Unicode字符串,我想将其转换为0.02浮点数:

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

And this is the output u'1/50' 这是输出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. 我正在编写一个程序,该程序将从JSON文件中提取信息,将来,我将需要转换相似的字符串,并且希望实现该过程的自动化。

You can split at / , convert to floats, and divide the numbers: 您可以在/分割,转换为浮点数,然后除以数字:

>>> num1, num2 = [float(x) for x in t.split('/')]
>>> num1 / num2
0.02

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM