1.内置数学函数
abs(x)
: 绝对值max(x1, x2,...)
: 最大值min(x1, x2,...)
:最小值pow(a, b)
: 与a ** b
效果相同round(x)
: 与 x 接近的整数,四舍五入round(x, n)
: 保留小数点后n位小数
2. math模块提供的数学函数
fabs
(浮点数的绝对值), ceil
, floor
, exp
, log
(自然对数), log(x, base)
, sqrt
, sin
,asin
, cos
, acos
, tan
, degree
(弧度转化为角度), radians
(角度转化为弧度)
3. 字符串和字符
- 字符串必须被包含在一对单引号( ’ )或者双引号( ” )之间。虽然两者都可以用,但是建议:用双引号来括住多个字符构成的字符串,用单引号来括住单个字符的字符串或者空字符串。
- 字符和ASCII码的互换
ord(ch)
返回字符ch的ASCII码chr(code)
返回code代表的字符
- 不换行打印(默认print会打印换行符)
print("ABC", end = '')
不换行print("ABC", end = ' ')
以空格结尾不换行print("ABC", end = '**')
以**结尾,不换行
- 字符串连接:使用加号 +连接两个字符串。
msg = "Welcome" + "to" + "Python"
4. 对象和方法简介
在Python中,所有的数据(包括数字和字符串)实际都是对象
可以用
id
和type
函数来获取关于对象的一些信息- 每次执行时Python都会自动为对象赋予一个独特的id, 在执行中不会发生改变
- 对象上的操作:
- s.lower()
- s.upper()
- s.strip() #去掉两边的空格(包括 ”, \t, \f, \r, \r 等)
5.格式化数字和字符串
使用格式:format(item, format-specifier)
如果format-specifier 为10.2f,意思是总长度为10,其中有2位是小数,不足10位的在前面补空格,小数不足两位的补0
print("Interest is", round(12313.5316, 2)) #只显示小数点后两位小数
print("Interest is", format(12313.0956, ".2f")) #保留两位小数
print(format(57.46754345, "10.2f"))
print(format(532342347.445, "10.2f"))
print(format(57.46754345, "10.2f"))
print(format(57.4, "10.2f"))
print(format(57, "10.2f"))
用科学计数法格式化
print(format(57.324234242, "10.2e"))
print(format(0.001243412423, "10.2e"))
print(format(57.4, "10.2e"))
print(format(57,"10.2e"))
结果:
__5.73e+01
__1.24e-03
__5.74e+01
__5.70e+01
其中下划线"_"代表空格,符号"+","-"被算在宽度里面。
格式化成百分数
print(format(0.53457, “10.2%”))
print(format(0.0033923, “10.2%”))
print(format(7.4, “10.2%”))
print(format(57, “10.2%”))
调整对齐格式
print(format(1322.543522,"<10.2f")) #以指定宽度左对齐
print(format(1322.543522,">10.2f")) #以指定宽度右对齐
格式化整数:d
, x
, o
, b
分别代表十进制、十六进制、八进制、二进制
print(format(5345345,”10d”))
print(format(5345345,”<10d”))
print(format(5345345,”10x”))
print(format(5345345,”>10x”))
格式化字符串(以 s 结尾)
print(format(“Welcome to Python”,”20s”))
print(format(“Welcome to Python”,”<20s”))
print(format(“Welcome to Python”,”>10s”))
print(format(“Welcome to Python”,”<10s”))