将使用'str()'的变量转换为数字

时间:2015-03-21 18:25:13

标签: python string python-2.7 parsing

我试图将math.floor函数应用于使用str()函数的一些变量......这样做的正确方法是什么?

这是我的代码:

import math
x = str(10.3)
y = str(22)
z = str(2020)

print "x equals " + x
print "y equals " + y
print "z equals " + z

#playing around with the math module here. The confusion begins...
#how do I turn my str() functions back into integers and apply the floor      function of the math module?
xfloor = math.floor(x)
zsqrt = math.sqrt(z)
print "When we print the variable \"xfloor\" it rounds " + x + "down into " + xfloor + "."
print "When we print the variable \"zsqrt\" it finds the sqareroot of " + z + "which is " + zsqrt + "."

raw_input("Press the enter key to continue.")

欢迎任何和所有的帮助。

1 个答案:

答案 0 :(得分:4)

把它们扔掉:

xfloor = math.floor(float(x))
zsqrt = math.sqrt(float(z))

但这不是推荐的做法,因为您不必要地将其转换为str。要print使用str.format

print "x equals {}".format(x)

为此,您无需转发str