2 - Python数学函数、字符串、对象
2015-09-19 15:37
246 查看
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”))
相关文章推荐
- 1 - Python 概述和基本知识
- Sublime Text 3 搭建Python开发环境
- Python快速过滤Numpy数组中特定元素的方法
- Python中的collections模块
- Python如何调用自己写的包
- PYTHON正成为中国互联网+的核心技术驱动力
- Ubuntu下配置Python进行数据处理的环境
- win8下sublime text2的安装和对python的环境配置
- 个人Python学习笔记
- Windows平台 python 常用包的安装
- 跟Python打包相关的一些文章
- win8下python安装和环境配置
- python正则匹配目录、文件名
- python datetime模块相关 mysql 时间戳等
- Python 基础语法_Python脚本文件结构
- 使用python创建一个检测不到的自定义SSH后门
- 使用python创建一个检测不到的自定义SSH后门
- gensim文档-相似性查询
- lsi计算文档相似度
- gensim的LSI模型来计算文档的相似度