前言
前几节了解了 Python 的不同数据类型, 有小伙伴会问, 不同的数据类型之间是否可以相互转换? 肯定是可以的, 本篇博文主要记录数字类型的转换, 其他类型的相互转换会在下几节记录, Here we go!
一, Python 数字类型转换
通过前几节, 我们知道 Python 数字的数据类型有: 整型, 长整型, 浮点型, 和复数, 它们之间是如何转换的呢? 亦或者它们是如何转换为其他数据类型呢? 先来看所有的方法:
- int(x [,base ]) # 将 x 转换为一个整数
- float(x ) # 将 x 转换到一个浮点数
- complex(real [,imag ]) # 创建一个复数
- str(x ) # 将对象 x 转换为字符串
- repr(x ) # 将对象 x 转换为表达式字符串
- eval(str ) # 用来计算在字符串中的有效 Python 表达式, 并返回一个对象
- tuple(s ) # 将序列 s 转换为一个元组
- list(s ) # 将序列 s 转换为一个列表
- chr(x ) # 将一个整数转换为一个字符
- ord(x ) # 将一个字符转换为它的整数值
- hex(x ) # 将一个整数转换为一个十六进制字符串
- oct(x ) # 将一个整数转换为一个八进制字符串
- bin(x) # 将一个整数转换为一个二进制字符串
我们先来申明一个变量 num1 = 6 , 之后用 type() 函数查看其数据类型, 任何数据类型都可以用此函数查看:
- In [103]: num1 = 6
- In [104]: type(num1)
- Out[104]: int
可以看到 num1 默认是 int 类型的, 再来创建 num2 = 6.6 , 再次查看其数据类型:
- In [105]: num2 = 6.6
- In [106]: type(num2)
- Out[106]: float
可以看到 num2 默认是 float 类型的, 也就是说, 当在 Python 中创建一个整数的时候, 默认的数据类型为 int , 创建一个小数的时候, 默认的数据类型是 float , 创建完后想要修改其数据类型就要用到上面的类型转换函数了
- In [110]: float(num1)
- Out[110]: 6.0
int 转换为 float
- In [114]: int(6.6)
- Out[114]: 6
- In [115]: int(-5.5)
- Out[115]: -5
- # int 函数会把小数位全部抹去, 保留整数部分
float 转换为 int
- In [116]: complex(5,8)
- Out[116]: (5+8j)
- # complex(实部, 虚部), 虚部可以省略
创建复数
- In [117]: str(5)
- Out[117]: '5'
- In [118]: str(6.6)
- Out[118]: '6.6'
数字转换为字符串
- In [123]: s = 'print("Hello,world!")'
- In [124]: s
- Out[124]: 'print("Hello,world!")'
- In [125]: eval(s)
- Hello,world!
- # 可以看到将字符串执行了
执行字符串的有效表达式
- In [130]: tuple([1,2,3])
- Out[130]: (1, 2, 3)
列表转换为元组
- In [139]: chr(56)
- Out[139]: '8'
- # 这里涉及 ASC 码的内容
整数转换为字符
- In [142]: ord('8')
- Out[142]: 56
- # 这里涉及 ASC 码的内容
字符转换为整数
- In [143]: hex(15)
- Out[143]: '0xf'
- # 十六进制的数以 0x 开头
整数转换为十六进制
- In [144]: oct(20)
- Out[144]: '0o24'
- # 八进制以 0o 开头
整数转换为八进制
- In [145]: bin(5)
- Out[145]: '0b101'
- # 二进制以 0b 开头
整数转化为二进制
- In [146]: import math
- In [147]: help(math)
- Help on built-in module math:
- NAME
- math
- DESCRIPTION
- This module is always available. It provides access to the
- mathematical functions defined by the C standard.
- FUNCTIONS
- acos(...)
- acos(x)
- Return the arc cosine (measured in radians) of x.
- acosh(...)
- acosh(x)
- Return the inverse hyperbolic cosine of x.
- asin(...)
- asin(x)
- Return the arc sine (measured in radians) of x.
- -- More --
- In [148]: dir(math)
- Out[148]:
- ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
- In [149]: import cmath
- In [150]: dir(cmath)
- Out[150]:
- ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
- In [173]: help(math.exp) # 注意是 math.exp, 不是 math.exp()
- Help on built-in function exp in module math:
- exp(...)
- exp(x)
- Return e raised to the power of x.
- abs(x) # 返回数字的绝对值, 如 abs(-10) 返回 10
- math.ceil(x) # 返回数字的上入整数, 如 math.ceil(4.1) 返回 5
- cmp(x, y) # 如果 x <y 返回 -1, 如果 x == y 返回 0, 如果 x> y 返回 1
- math.exp(x) # 返回 e 的 x 次幂(ex), 如 math.exp(1) 返回 2.718281828459045
- math.fabs(x) # 返回数字的绝对值, 如 math.fabs(-10) 返回 10.0
- math.floor(x) # 返回数字的下舍整数, 如 math.floor(4.9)返回 4
- math.log(x) # 如 math.log(math.e)返回 1.0,math.log(100,10)返回 2.0
- math.log10(x) # 返回以 10 为基数的 x 的对数, 如 math.log10(100)返回 2.0
- max(x1, x2,...) # 返回给定参数的最大值, 参数可以为序列.
- min(x1, x2,...) # 返回给定参数的最小值, 参数可以为序列.
- math.modf(x) # 返回 x 的整数部分与小数部分, 两部分的数值符号与 x 相同, 整数部分以浮点型表示.
- math.pow(x, y) # x**y 运算后的值.
- round(x [,n]) # 返回浮点数 x 的四舍五入值, 如给出 n 值, 则代表舍入到小数点后的位数.
- math.sqrt(x) # 返回数字 x 的平方根
- In [159]: import math
- In [160]: exp(2)
- ---------------------------------------------------------------------------
- NameError Traceback (most recent call last)
- <ipython-input-160-840a487878a2> in <module>
- ----> 1 exp(2)
- NameError: name 'exp' is not defined # 不加前缀表示这个方法没有被定义
- In [161]: math.exp(2) # 加上前缀就可以正常使用了
- Out[161]: 7.38905609893065
- math.acos(x) # 返回 x 的反余弦弧度值.
- math.asin(x) # 返回 x 的反正弦弧度值.
- math.atan(x) # 返回 x 的反正切弧度值.
- math.atan2(y, x) # 返回给定的 X 及 Y 坐标值的反正切值.
- math.cos(x) # 返回 x 的弧度的余弦值.
- math.hypot(x, y) # 返回欧几里德范数 math.sqrt(x*x + y*y).
- math.sin(x) # 返回的 x 弧度的正弦值.
- math.tan(x) # 返回 x 弧度的正切值.
- math.degrees(x) # 将弧度转换为角度, 如 math.degrees(math.pi/2) , 返回 90.0
- math.radians(x) # 将角度转换为弧度
- math.pi # 数学常量 pi(圆周率, 一般以π来表示)
- math.e # 数学常量 e,e 即自然常数(自然常数).
- In [164]: math.pi
- Out[164]: 3.141592653589793
- In [165]: math.e
- Out[165]: 2.718281828459045
- In [171]: import random
- In [172]: dir(random)
- Out[172]:
- ['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
- random.choice(seq) # 从序列的元素中随机挑选一个元素, 比如 random.choice(range(10)), 从 0 到 9 中随机挑选一个整数.
- random.randrange ([start,] stop [,step]) # 从指定范围内, 按指定基数递增的集合中获取一个随机数, 基数缺省值为 1
- random.random() # 随机生成下一个实数, 它在 [0,1) 范围内.
- random.seed([x]) # 改变随机数生成器的种子 seed. 如果你不了解其原理, 你不必特别去设定 seed,Python 会帮你选择 seed.
- random.shuffle(lst) # 将序列的所有元素随机排序
- random.uniform(x, y) # 随机生成下一个实数, 它在 [x,y] 范围内.
来源: https://www.cnblogs.com/minutesheep/p/10322828.html