Python-数字转换
时间:2020-02-23 14:43:04 来源:igfitidea点击:
在本教程中,我们将在Python中进行一些数字转换练习。
我们在上一教程中已经介绍了Numbers,所以请随时检查一下。
类型转换
当其中存在混合数据类型时,Python负责数据类型转换,以便我们正确评估表达式。
这也称为隐式类型转换。
但是,如果我们必须明确地告诉Python将变量转换为特定类型,我们也会遇到这种情况。
这也称为显式类型转换。
以下是用于转换数字数据类型的函数。
- int
- float
- complex
int()
函数
我们使用int()函数将值显式转换为整数类型。
注意点!
如果该值包含小数点,则小数部分将被截断。
如果我们有一个整数值(例如" 10")的字符串值,那么它将被转换为整数。
在下面的示例中,我们将值转换为int。
# variables x = "10" # converting from string to int y = 123.45 # converting from float to int # convert updated_x = int(x) updated_y = int(y) # output print("x:", x, "is", type(x)) print("updated_x:", updated_x, "is", type(updated_x)) print("y:", y, "is", type(y)) print("updated_y:", updated_y, "is", type(updated_y))
我们将获得以下输出。
x: 10 is <class 'str'> updated_x: 10 is <class 'int'> y: 123.45 is <class 'float'> updated_y: 123 is <class 'int'>
float()
函数
我们使用float()
函数将值显式转换为float类型。
注意点!
如果该值是整数,则将添加小数部分。
如果我们有一个浮点数的字符串值(例如" 3.14"),那么它将转换为浮点数。
在下面的示例中,我们将值转换为float。
# variables x = "3.14" # converting from string to float y = 123 # converting from int to float # convert updated_x = float(x) updated_y = float(y) # output print("x:", x, "is", type(x)) print("updated_x:", updated_x, "is", type(updated_x)) print("y:", y, "is", type(y)) print("updated_y:", updated_y, "is", type(updated_y))
我们将获得以下输出。
x: 3.14 is <class 'str'> updated_x: 3.14 is <class 'float'> y: 123 is <class 'int'> updated_y: 123.0 is <class 'float'>
complex()
函数
我们使用complex()
函数将值显式转换为复杂类型。
在下面的示例中,我们将值" x"转换为复数形式,其中" x"是复数的实数部分。
# variable x = 10 # real part of the complex number # convert result = complex(x) # output print("x:", x, "is", type(x)) print("result:", result, "is", type(result))
我们将获得以下输出。
x: 10 is <class 'int'> result: (10+0j) is <class 'complex'>
在下面的示例中,我们将值x和y转换为复数形式,其中x是复数的实部,而y是虚部。
# variable x = 10 # real part of the complex number y = 20 # imaginary part of the complex number # convert result = complex(x, y) # output print("x:", x, "is", type(x)) print("y:", y, "is", type(y)) print("result:", result, "is", type(result))
我们将获得以下输出。
x: 10 is <class 'int'> y: 20 is <class 'int'> result: (10+20j) is <class 'complex'>