2 - Python数学函数、字符串、对象

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中,所有的数据(包括数字和字符串)实际都是对象

  • 可以用idtype函数来获取关于对象的一些信息

    • 每次执行时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”))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值