python3系列(2)-数据类型

变量

Python 中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。

标识符(变量名):命名规则

  1. 以Unicode编码的字母开头,不能以数字开头
  2. 不能与关键字冲突
  3. 大小写敏感,区分大小写
  4. 以下划线开头的变量名有特殊用途
  5. 建议使用驼峰式命名规则

关键字列表

import keyword
print(keyword.kwlist)

[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

使用type()函数获取变量类型 使用id()查看变量的内存地址

dir()返回内置属性列表 dir(builtins) 返回内置属性列表

变量赋值使用 = 可使用连续赋值,例如 n3=n2=n1=15

###是否同一变量判断

is

数据类型

内置数据类型:整型、布尔型

标准库数据类型:前提是导入相对应的模块

整型

分类:整数、浮点数、复数 python3中整数没有长度限制,根据运行的机器的内存大小为最大长度限制

1 + 2  # >3
1 - 2  # -1
2 * -3  # >-6
2 / -3  # > -0.6666666666666666
5 // 3  # >1  除法取商,舍弃小数部分取整
-5 % 3  # > 1 商是-2,余数是1
5 % 3  # > 2
5**-2  # > 0.04 ,求5的-2次方幂
abs(-1.9)  # > 1.9取绝对值
# divmod返回元组((x-x%y)/y,x%y)
divmod(-5, 3)  # > (-2,1),由商和余数组成的元组
pow(5, -2)  # >0.04等价于5**-2
# pow(x,y,z)类似(x**y)%z,当有第3个参数时,第2个不能取负数
pow(5, 2, 2)  # > 1
round(-1.6)  # > 结果四舍五入 -2
routn(3.546,2) # > 3.55 ,其中第二个参数表示小数部分的位数
math.ceil(18.1)  # > 19 向上取整
math.floor(18.9)  # > 18 向下取整
math.sqrt(16)  # > 4.0 开平方
bin(-10)  # > 结果是字符串类型'-0b1010'
type(hex(-10))  # 结果是字符串 <class 'str'>
int(-1.9)  # >截取整数部分 -1
int('12', 11)  # > 13 表示进制是11的整数12转成10进制后的结果

布尔型

··· 5 and 6 # > 6 5 or 6 # > 5 not 6 # > False 0 or 1 # > 1 ···

字符串

字符串的内置函数

'abc'.capitalize()  # > 'Abc'
# 不可变序列可使用in,+=,*=等操作
str1='abcdefg'
str1.center(3)  # > 'abcdefg'
str1.center(10, '*')  # > '*abcdefg**'
str1.count('d')  # >  1
str1.count('m', 6) == str1[6:].count('m')  # > True,两者等价
str1.encode('utf8')  # >得到二进制 b'abcdefg'
str1.endswith('g')  # > True
str1.startswith('a')  # >True 判断是否以指定字符开头
# str1.expandtabs(size) 返回str1的一个副本,将制表符换成8个或者size个空格
str1.find('b', 3, 6)  # > -1 返回从第3到第6个字符之间出现b的最左边的索引值,如果没有则返回-1
# str1.index('b',3,6) #> 出现ValueError错误,功能类似find,但是找不到时报错
str1.rindex('b')  # > 1  从右向左找,返回索引值
str1.isalnum()  # > True 如果strr1非空,并且每个字符都是字母数字,则返回True
str1.isalpha()  # > True 判断字符串是否全都是字母
str1.isdigit()  # >False  判断是否全都是数字
str1.isdecimal()  # > False 判断是否都是Unicode基数为10的数字
str1.isidentifier()  # > True 判断是否每个字符都是有效的字符
str1.islower()  # > True 判断字符串中至少有一个可小写字母,并且所有字母小写
str1.isnumeric()  # > False
str1.isprintable()  # > True,有换行符时返回False
str1.isspace()  # > False 如果字符串非空,每个字符都是空白字符,则返回True,制表符也认为空白符
str1.istitle()  # > False,非空且首字母大写的字符串则返回True
str1.isupper()  # > False 类似islower,判断是否都大写
'*'.join(str1)  # > 'a*b*c*d*e*f*g' 把前面的字符插入到后面字符串的每个字符之间
str1.ljust(10, '*')  # > 'abcdefg***' 补齐到10,左对齐,右侧用'*'填充
str1.lower()  # > 'abcdefg' 把字母变小写
str1.upper()  # > 'ABCDEFG'把能大写的都变大写
str1.partition('b')  # ('a','b','cdefg')返回元组,分隔符左边,分隔符,分隔符右边
str1.partition('s')  # ('abcdefg','','')返回元组
str2 = 'abcdb123'
str2.partition('b')  # >('a','b','cdb123')
str2.rpartition('b')  # > ('abcd','b','123')
# s.replace(t,u,n) 返回s的副本,其中每个t使用u替换,最多替换n个
str2.replace('b', 'B', 3)  # > 'aBcdB123'
str2.split('b')  # >得到列表['a','cd','123']按指定字符分割,最多分n次,即最多n+1个元素
str2.splitlines()  # > 以换行符分割
str2.strip()  # > 'abcdb123' 将两头的空白字符去掉
str2.lstrip()  # > 只去掉开头的空白
str2.rstrip()  # > 只去掉结尾的空白
str2.swapcase()  # > 'ABCDB123' 大小写字母互换
str2.title()  # > 'Abcdb123'
str2.zfill(10)  # > '00abcdb123' 补齐到10,左侧用0填充

len(str2)  # > 8  返回字符串中字符的个数

str3 = reversed(str2)  # 得到的一个迭代对象<reversed object at  0x000>,使用时才能抽取到元素
''.join(reversed(str2))  # > '321bdcba' 通过join运算迭代使用反转后的各个元素
str2[::-1]  # > '321bdcba'效果与上面一样

更多字符串的内置函数,通过dir命令查看,

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '_
_eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs
__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__'
, '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__'
, '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'e
ncode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isal
num', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstr
ip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartitio
n', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase'
, 'title', 'translate', 'upper', 'zfill']
>>>
>>> help(str.rfind)
Help on method_descriptor:

rfind(...)
    S.rfind(sub[, start[, end]]) -> int

    Return the highest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

>>>

字符串截取示例

如下函数实现从一段字符串中截取标签内的内容,例如从"what a <red>rose</red>"中抽取tag为red中间的数据

def extract_from_tag1(tag, line):
    opener = "<" + tag + ">"
    closer = "</" + tag + ">"
    try:
        i = line.index(opener)
        start = i + len(opener)
        j = line.index(closer, start)
        return line[start, j]
    except ValueError:
        return None


def extract_from_tag2(tag, line):
    opener = "<" + tag + ">"
    closer = "</" + tag + ">"
    i = line.find(opener)
    if i != -1:
        start = i + len(opener)
        j = line.find(closer, start)
        if j != -1:
            return line[start:j]
    return None

运算符

Table of Contents