如何在 Python 中将字符串更改为十进制并将值设置为 2 dp (3.6)



抱歉,我最初的解释似乎不清楚,所以我尽可能地更新了以下内容。

我通过将数据文件

切片,从字段列表和固定宽度的数据文件创建了一个字典。

data_format_keys = {
            ("CURRENT-RATIO", 120, 127),
            ("ACID-TEST", 127, 134),
            ("NOTES", 134, 154 
            }

打印出来时,我得到以下信息...

Current Ratio = 1234
Acid Test = 5678
Notes = These are my notes

对于电流比率 (1234) 和酸性测试 (5678) 中的数据,我需要将字符串转换为数字并插入小数点以用于计算(这些字段来自大型机文件,因此需要转换为正确的格式)。

预期输出为...

Current Ratio = 12.34    #This is an integer/float
Acid Test = 5.678    #This is an integer/float
Notes = These are my notes    #This is still a string

我已经创建了一个需要从原始列表转换的字段列表,但我正在努力解决如何应用转换

        for k,v in data_format_keys.items():
            if k in data_format_keys == headerdict[i[1]]:
                line = line.replace(k, v)
        fo.write(line)
print(headerdict)

其中 headerdict 是创建的初始字典,data_format_keys 是要转换的字段列表。

有什么想法吗? 谢谢

如果您愿意,可以使用格式化输出。

下面是一个示例:

#Inputs
meal_cost = float(input("Enter meal price: "))
drink_cost = float(input("Enter drinks cost: "))
#Calculation
total_cost = meal_cost + drink_cost
#Output
print("Your total bill is {:.2f} USD".format(total_cost))

您的输出将如下所示:

Enter meal price: 7.49
Enter drinks cost: 2.99
Your total bill is 10.48 USD

让我知道这是否有帮助。 :)

试试这个:

#createlist from current output
thelist = [('Current Ratio', 1234), ('Acid Test', 5678), ('Notes', 'These are my notes') ]
#create dict with just notes
notes = dict([i for i in thelist if i[0] == "Notes"])
#create list without notes
thelist = [i for i in thelist if i[0] != "Notes"]
#create list of keys
thelist1 = [i[0] for i in thelist]
#create list of formatted numbers
thelist2 = [float(i[1]/100) for i in thelist]
#merge into dict
thelist = dict(zip(thelist1, thelist2))
#create empty dict
desired = {}
#update dict with previously created dicts
desired.update(thelist)
desired.update(notes)
print (desired)

更擅长python的人可能能够编写更有效的代码,但这应该是一个很好的起点。

最新更新