python零零****基础day3基本类型之数值与字符串
数值类型:在JAVA中 5/2 = 2的 而在python中 5/2 = 2.5
format: '{0}'.format(20) => 输出为 ‘20’
‘3+2={0}’.format(5) => '3+2 = 5'
f = 3.3333333333333
'f={0:.2f}'.format(f) => 'f=3.33' 保留小数位后面两位小数
/ 表示除。 如果有小数就带小数,没有就返回出一个整数.
//表示除之后取整.
例:10/4 = 2.5 ; 10//4 = 2; 10//4.0 = 2.0. 除法后保留到除数中精度最高的那一位.
数字类型中也可以自己引入一个包。常用的例如有 math。 里面封装了许多可以直接调用的方法.
import math
math.sqrt(144) => 12.0
sqrt开平方
math.floor(3.4) => 3
math.floor(3.9) =>3
math.floor(-3.4) => -4
math.floor(-3.9) => -4
floor方法 向左取整.
math.trunc(3.14) =>3
math.trunc(3.94) =>3
math.trunc(-3.14) =>-3
math.trunc(-3.94) =>-3
trunc表示截断小数位的取整。
round(3.14) => 3
round(3.94) => 4
round(-3.14) => -3
round(-3.94) => -4
round表示四舍五入之后取整.
但是round函数里面有点小坑.在 python3中 round(0.5)和round(-0.5)返回的都是 0.
但在python2中都返回1.
因为
在python2.7的doc中,round()的最后写着,"Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0." 保留值将保留到离上一位更近的一端(四舍六入),如果距离两端一样远,则保留到离0远的一边。所以round(0.5)会近似到1,而round(-0.5)会近似到-1。
但是到了python3.5的doc中,文档变成了"values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice." 如果距离两边一样远,会保留到偶数的一边。比如round(0.5)和round(-0.5)都会保留到0,而round(1.5)会保留到2。
所以如果有项目是从py2迁移到py3的,可要注意一下round的地方(当然,还要注意/和//,还有print,还有一些比较另类的库)。
八进制: 0o3 = 3 oct(64) = '0o100'
二进制:0b0 = 0 ; 0b11 = 3; bin(64) = 0b1000000
如果对精度追求比较高的话,我们可以引用Decimal包来进行数学的计算。
impore decimal
decimal.Decimal(1.1) = > Decimal('1.100000000000000088817841970012523233890533447265625')
我们看到会发生很奇怪的结果。因为我们在括号里直接放入了一个数字类型。这样不太好。
decimal.Decimal('1.1') =>Decimal('1.1')
decimal.Decimal('1.1') + decimal.Decimal('2.2') => Decimal('3.3')
而如果直接计算 1.1+2.2 就会有精度的缺失.
转译符:用 ‘\’+ 符号
如果我们想输出句话: 'what's your name'。 在python中就会报错,因为他会把 's中的' 当成单引号与前面的配对
所以我们可以 'what\'s your name' 这样就会输出 "what's your name"
path = 'C:\abc\xyz.txt' 也会报错 ,我们只能 path = 'C:\\abc\\xyz.txt'.
但这样也会很麻烦,所以python中我们也可以这样写:path = r'C:\abc\xyz.txt' ;前面加上一个r就可以了.
注释:在python 中可以用 """这是一行注释 """ 或者 '''这是一行注释''' 或者#这是一行注释
字符串:
s = 'abcdefghijklmn'
s[0:4] => 'abcd'
s[-1] = s[len(s)-1] => 'n'
s[:] => 'abcdefghijklmn'
s[::2] => 'acegikm'
s[::-1] => 'nmlkjihgfedcba'
int('42') +1 => 43
h = 'hello'
h.replace('e','a') => 'hallo'