Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 字符串切片和操作_Python - Fatal编程技术网

Python 字符串切片和操作

Python 字符串切片和操作,python,Python,价格是来像48600.0,但实际价格是4.86美元,所以我这样做 last_price3 = str(x["last_price_4d"]) #48600.0 last_price2 = last_price3[0:1] + "." + last_price3[:-4] last_price = float(last_price2) 我可以像上面那样做,但是如果价格前面有超过1个数字,比如176.85美元,该怎么办 最后的价格将是1768500.0 谢谢价格除以10000怎么样,因为它是按比例

价格是来像48600.0,但实际价格是4.86美元,所以我这样做

last_price3 = str(x["last_price_4d"]) #48600.0
last_price2 = last_price3[0:1] + "." + last_price3[:-4]
last_price = float(last_price2)
我可以像上面那样做,但是如果价格前面有超过1个数字,比如176.85美元,该怎么办 最后的价格将是1768500.0


谢谢

价格除以10000怎么样,因为它是按比例计算的

last_price = round(x["last_price_4d"] / 10000, 2)

如果数字被缩放为10000倍大,您可以进行除法,但是如果您确实想通过字符串操作进行除法,您可以进行除法

last_price3 = str(x["last_price_4d"])
i = last_price3.index('.')
last_price = last_price3[:i-2][:-2]+'.'+last_price3[:i-2][-2:]

您需要找到“.”的索引,它比字符串操作更有效,而且非常简单straightforward@OlivierMelan谢谢你!注意:如果有人仍在使用Python 2,并且在某些情况下,
last\u price\u 4d
可能是int而不是float,那么除以
10000.0
(即
float(10000)
)会更安全,以避免舍入错误。例如,
48600
将使用上述代码生成4.0而不是4.86。在Python3中,此解决方案适用于浮点和整数:-)