数据类型和结构

1)基本数据类型(三种):int整数、float浮点数、str字符串

2)基本数据结构(六种)

一、int整数:ptyhon整数可以为任意大。解释程序简单地使用所需的位/字节数表现数值

a = 10
### 获得类型
type(a) # int
### 获得所需的位数
a.bit_length() # 4
a = 100000
a.bit_length() # 17

二、float浮点数:注意整数运算和浮点数运算可能有差异

  • import decimal
  • from decimal import Decimal
f = 1. # 1.0
f = 0.1
浮点对象在内部总是只表现为某种精度
0.35 + 0.1 # 0.44999999999999996

### 任意精度浮点数
# decimal模块提供一个任意精度浮点数对象。在金融中,确保高精度、超出64位双精度标准有时是必要的。
import decimal
from decimal import Decimal
decimal.getcontext() # 获得Context对象的所有属性值,可以改变表示精度
Decimal(1) / Decimal(1) # 默认prec = 28位小数精度
decimal.getcontext().prec = 4 # 保留4位小数精度

三、str字符串:解析字符串对象时,考虑使用正则表达式,带来便利和高性能

  • import re
  • reg = re.compile("xxxxx")
  • res = reg.findall( str )
s = 'this is a string object'
s.capitalize() # 首字母大写
s.split() # 返回拆分后的数组
s.find('string') # 返回找到的第一个字母的索引值,否则返回-1
s.replace(' ', '|') # 替换字符串