如何在Python中将数字字符串转换为float

时间:2017-09-21 16:30:16

标签: python

我是Python新手并尝试将程序从Java迁移到Python。 在这个应用程序中,我将读取一个文本文件,并将根据记录类型处理数据。 每个记录存储一个金额值为12个字符,即22.10将存储为000000002210。

在Java中,我会执行以下操作将000000002210转换为22.10

class Pitch_Class_Set(object):

    def __init__(self, pitches):
        self.pitches = pitches
        print(self.pitches)
        print(list(set([int(i) % 12 for i in self.pitches.split()])).sort())

setterino = Pitch_Class_Set(input('> '))

任何人都可以帮助我使用Python做同样的事情。

请注意,我在Windows 7中使用Python2.7。

2 个答案:

答案 0 :(得分:1)

假设总有两个小数位,您可以将string转换为int,然后除以100。 Python会自动将int转换为float类型。

所以你可以这么做:

s = "000000002210"
print(int(s) / 100)

将输出:

22.1

答案 1 :(得分:1)

首先,您需要将数字字符串转换为float,然后使用formatpyformat

s='00002210'
d = format(float(s)/100,'.02f')
print(d)

输出:

22.10