python数据类型之内置方法
Posted Eurekaa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python数据类型之内置方法相关的知识,希望对你有一定的参考价值。
python有六大数据类型,分别为整型、字符串、列表、字典、元祖和集合,这些基本数据类型都内置了很多方法,接下来一一探寻。
一 整型
python中整型有两种:int和float
1 int
使用dir函数查看有多少内置方法
# python3.x dir(int) # [‘__abs__‘, ‘__add__‘, ‘__and__‘, ‘__bool__‘, ‘__ceil__‘, ‘__class__‘, ‘__delattr__‘, ‘__dir__‘, ‘__divmod__‘, ‘__doc__‘,
‘__eq__‘, ‘__float__‘, ‘__floor__‘, ‘__floordiv__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getnewargs__‘, ‘__gt__‘,
‘__hash__‘, ‘__index__‘, ‘__init__‘, ‘__int__‘, ‘__invert__‘, ‘__le__‘, ‘__lshift__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘,
‘__neg__‘, ‘__new__‘, ‘__or__‘, ‘__pos__‘, ‘__pow__‘, ‘__radd__‘, ‘__rand__‘, ‘__rdivmod__‘, ‘__reduce__‘, ‘__reduce_ex__‘,
‘__repr__‘, ‘__rfloordiv__‘, ‘__rlshift__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__ror__‘, ‘__round__‘, ‘__rpow__‘, ‘__rrshift__‘, ‘__rshift__‘,
‘__rsub__‘, ‘__rtruediv__‘, ‘__rxor__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__sub__‘, ‘__subclasshook__‘, ‘__truediv__‘, ‘__trunc__‘,
‘__xor__‘, ‘bit_length‘, ‘conjugate‘, ‘denominator‘, ‘from_bytes‘, ‘imag‘, ‘numerator‘, ‘real‘, ‘to_bytes‘] # python 2.x dir(int) # [‘__abs__‘, ‘__add__‘, ‘__and__‘, ‘__class__‘, ‘__cmp__‘, ‘__coerce__‘, ‘__delattr__‘, ‘__div__‘, ‘__divmod__‘, ‘__doc__‘,
‘__float__‘, ‘__floordiv__‘, ‘__format__‘, ‘__getattribute__‘, ‘__getnewargs__‘, ‘__hash__‘, ‘__hex__‘, ‘__index__‘, ‘__init__‘,
‘__int__‘, ‘__invert__‘, ‘__long__‘, ‘__lshift__‘, ‘__mod__‘, ‘__mul__‘, ‘__neg__‘, ‘__new__‘, ‘__nonzero__‘, ‘__oct__‘, ‘__or__‘,
‘__pos__‘, ‘__pow__‘, ‘__radd__‘, ‘__rand__‘, ‘__rdiv__‘, ‘__rdivmod__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rfloordiv__‘,
‘__rlshift__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__ror__‘, ‘__rpow__‘, ‘__rrshift__‘, ‘__rshift__‘, ‘__rsub__‘, ‘__rtruediv__‘, ‘__rxor__‘,
‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__sub__‘, ‘__subclasshook__‘, ‘__truediv__‘, ‘__trunc__‘, ‘__xor__‘, ‘bit_length‘, ‘conjugate‘,
‘denominator‘, ‘imag‘, ‘numerator‘, ‘real‘]
因为是整型类型,所以有加减乘除、取绝对值的方法,像__abs__是取绝对值,__add__是加法等,其中重要的几个方法是:bit_length、conjugate、from_bytes、imag、numerator、real、to_bytes
digit = 123 print(digit.bit_length()) # 进入源码,Number of bits necessary to represent self in binary # 首先把int型转为二进制,然后计算二进制的位数
num = 2.3 - 2.5j result = num.real #复数的实部 print(result) #打印输出2.3 result = num.imag #复数的虚部 print(result) #打印输出2.5j result = num.conjugate() #返回该复数的共轭复数 print(result) #打印输出(2.3+2.5j)
print(int.from_bytes(bytes=b‘A‘, byteorder=‘little‘) #打印输出 65 ,即将字符A转换为十进制
num = 2 result = num.to_bytes(5,byteorder=‘little‘) print(result) #打印输出b‘x02x00x00x00x00‘ for i in result: print(i) #打印输出2 0 0 0 0 # 表示回车
imag、real分别是计算出复制的实部和虚部,conjugate得出共轭复数,numerator不知道什么鬼。
2 str
#python3.5 dir(str) #[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘,
‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘,
‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘,
‘__subclasshook__‘, ‘capitalize‘, ‘casefold‘, ‘center‘, ‘count‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘, ‘format_map‘,
‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdecimal‘, ‘isdigit‘, ‘isidentifier‘, ‘islower‘, ‘isnumeric‘, ‘isprintable‘, ‘isspace‘, ‘istitle‘, ‘isupper‘,
‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘, ‘maketrans‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘,
‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘] #python2.7 dir(str) #[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘,
‘__getnewargs__‘, ‘__getslice__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘,
‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘,
‘_formatter_field_name_split‘, ‘_formatter_parser‘, ‘capitalize‘, ‘center‘, ‘count‘, ‘decode‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘,
‘find‘, ‘format‘, ‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdigit‘, ‘islower‘, ‘isspace‘, ‘istitle‘, ‘isupper‘, ‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘,
‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘,
‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]
# 计算字符串中某个字符的总数 str1 = ‘aaabc‘ print(str1.count(‘a‘)) # 输出结果为 3
capitalize
# 编码 默认为utf-8(Unicode) str1 = ‘aaabc‘ print(str1.encode()) # 输出结果为 b‘aaabc‘
# 判断字符串是否已某个字符结束,返回值为布尔值 str1 = ‘aaabc‘ print(str1.endswith(‘c‘)) # 输出结果为 True
# 找到字符串中某个字符第一次出现的索引 str1 = ‘aaabc‘ print(str1.find(‘a‘)) # 输出结果为 0
# 返回某个字符第一次出现的索引 str1 = ‘aaabc‘ print(str1.index(‘a‘)) # 输出结果为 0
# 判断字符串中字符是否都是数字,返回一个布尔值 str1 = ‘aaabc‘ print(str1.isdigit()) # 输出结果为 False str2 = ‘123‘ print(str2.isdigit()) # 输出结果为 True
# 判断字符串中的字符是否全为小写 S = ‘abc‘ print(S.islower()) # 输出结果为True S = ‘123‘ print(S.islower()) # 输出结果为False
# 判断S中字符是否全为大写 S = ‘ABC‘ print(S.isupper()) # 输出结果为True S = ‘123‘ print(S.isupper()) # 输出结果为False
# 将S中的字符用分隔符分隔 S = ‘abcd‘ print(‘.‘.join(S)) # 输出结果为 a.b.c.d
# 将S中的字符全改为小写 S = ‘AbCd123‘ print(S.lower()) # 输出结果为 abcd123
# 将S中左边的空格去掉 S = ‘ AbCd123‘ print(S.lstrip()) # 输出结果为 AbCd123
# 将S中的字符用字符替换 S = ‘AbCd123‘ print(S.replace(‘A‘, ‘a‘)) # 输出结果为 abCd123
S = ‘AbCd123‘ print(S.split(‘d‘)) # 输出结果为 [‘AbC‘, ‘123‘]
# 判断S是否以某个字符开始,返回一个布尔值 S = ‘AbCd123‘ print(S.startswith(‘A‘)) # 输出结果为 True S = ‘AbCd123‘ print(S.startswith(‘d‘)) # 输出结果为 False
# 将S左右两边的空格去掉 S = ‘ AbCd123 ‘ print(S.strip()) # 输出结果为 AbCd123
# 将S中所有的字符大写 S = ‘AbCd123 ‘ print(S.upper()) # 输出结果为 ABCD123
3 list
# python 3.x dir(list) # [‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘,
‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__iadd__‘, ‘__imul__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘,
‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__reversed__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__setitem__‘,
‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘append‘, ‘clear‘, ‘copy‘, ‘count‘, ‘extend‘, ‘index‘, ‘insert‘, ‘pop‘, ‘remove‘,
‘reverse‘, ‘sort‘] # python 2.x dir(list) # [‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__delslice__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘,
‘__getattribute__‘, ‘__getitem__‘, ‘__getslice__‘, ‘__gt__‘, ‘__hash__‘, ‘__iadd__‘, ‘__imul__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘,
‘__lt__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__reversed__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__setitem__‘,
‘__setslice__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘append‘, ‘count‘, ‘extend‘, ‘index‘, ‘insert‘, ‘pop‘, ‘remove‘, ‘reverse‘, ‘sort‘]
# 往列表追加元素 lis = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] lis.append(4) print(lis) # 输出结果 [‘a‘, ‘b‘, ‘c‘, 1, 2, 3, 4]
# 清空列表 lis = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] lis.clear() print(lis) # 输出结果 []
# 拷贝一个列表并返回该列表 lis = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] lis1 = lis.copy() print(lis1) # 输出结果 [‘a‘, ‘b‘, ‘c‘, 1, 2, 3]
# 计算列表中某个元素的数量 lis = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] lis1 = lis.copy() print(lis1) # 输出结果 [‘a‘, ‘b‘, ‘c‘, 1, 2, 3]
# 合并列表 lis1 = [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] lis2 = [4, 5, 6, 7, 8] lis1.extend(lis2) print(lis1) # 输出结果 [‘a‘, ‘b‘, ‘c‘, 1, 2, 3, 4, 5, 6, 7, 8]
# 返回列表中元素的第一个出现位置的索引 lis1 = [‘a‘, ‘a‘, ‘b‘, ‘c‘, 1, 2, 3] ind = lis1.index(‘a‘) print(ind) # 输出结果 0
# 插入到列表中某个索引位置 lis1 = [‘a‘, ‘a‘, ‘b‘, ‘c‘, 1, 2, 3] lis1.insert(4, ‘d‘) print(lis1) # 输出结果 [‘a‘, ‘a‘, ‘b‘, ‘c‘, ‘d‘, 1, 2, 3]
# 弹出列表中某个索引位置的值,默认弹出最后一个 lis1 = [‘a‘, ‘a‘, ‘b‘, ‘c‘, 1, 2, 3] lis1.pop() print(lis1) # 输出结果 [‘a‘, ‘a‘, ‘b‘, ‘c‘, ‘d‘, 1, 2, ] lis1 = [‘a‘, ‘a‘, ‘b‘, ‘c‘, 1, 2, 3] lis1.pop(4) print(lis1) # 输出结果 [‘a‘, ‘a‘, ‘b‘, ‘c‘, ‘d‘, 2, 3]
# 删除列表中的元素 lis1 = [‘a‘, ‘a‘, ‘b‘, ‘c‘, 1, 2, 3] a = lis1.remove(‘a‘) print(lis1) # 输出结果 [‘a‘, ‘b‘, ‘c‘, 1, 2, 3] # 和pop方法不同的地方有两个:pop通过索引取出值,有返回值;remove通过元素删除,没有返回值
# 反转列表 lis1 = [‘a‘, ‘a‘, ‘b‘, ‘c‘, 1, 2, 3] lis1.reverse() print(lis1) # 输出结果 [3, 2, 1, ‘c‘, ‘b‘, ‘a‘, ‘a‘]
# 排序 lis1 = [‘a‘, ‘a‘, ‘b‘, ‘c‘, ‘r‘, ‘c‘, ‘g‘, ‘l‘] lis1.sort() print(lis1) # 输出结果 [‘a‘, ‘a‘, ‘b‘, ‘c‘, ‘c‘, ‘g‘, ‘l‘, ‘r‘]
4 dict
#python3.x dir(dict) #[‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘,
‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘,
‘__repr__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘clear‘, ‘copy‘, ‘fromkeys‘, ‘get‘, ‘items‘, ‘keys‘,
‘pop‘, ‘popitem‘, ‘setdefault‘, ‘update‘, ‘values‘] #python2.x dir(dict) #[‘__class__‘, ‘__cmp__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘,
‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘,
‘__repr__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘clear‘, ‘copy‘, ‘fromkeys‘, ‘get‘, ‘has_key‘, ‘items‘,
‘iteritems‘, ‘iterkeys‘, ‘itervalues‘, ‘keys‘, ‘pop‘, ‘popitem‘, ‘setdefault‘, ‘update‘, ‘values‘, ‘viewitems‘, ‘viewkeys‘, ‘viewvalues‘]
# 清空字典 dic = {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘} dic.clear() print(dic) # 输出结果 {}
# 拷贝字典 dic = {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘} dic1 = dic.copy() print(dic1) # 输出结果 {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘}
# 返回一个新的字典 dic = {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘} dic1 = dic.fromkeys((‘l‘), (‘hashangda‘)) print(dic1) print(dic) # 输出结果 [‘l‘: ‘hashangda‘} # {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘} # 不改变前面的字典
# 通过key取值,如果取不到也不报错 dic = {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘} name1 = dic.get(‘name‘) other = dic.get(‘school‘) print(name1) print(other) # 输出结果 szz,None
# 获取字典的key和value dic = {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘} for key, value in dic.items(): print(key, value) # 输出结果 name szz age 18 addr shanghai
# 获取字典所有的键值 dic = {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘} keys = dic.keys() print(keys) # 输出结果 dict_keys([‘name‘, ‘age‘, ‘addr‘])
# 弹出字典中的键值对 dic = {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘, ‘school‘: ‘hashangda‘} item = dic.pop(‘name‘) print(item) print(dic) # 输出结果 szz {‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘, ‘school‘: ‘hashangda‘}
# 弹出字典中最后一个键值对 dic = {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘, ‘school‘: ‘hashangda‘} item = dic.popitem() print(item) print(dic) # 输出结果 (‘school‘, ‘hashangda‘) {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘} # 弹出的键和值用列表存储
# 给字典设置默认值 dic = {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘, ‘school‘: ‘hashangda‘} dic.setdefault(‘male‘, 1) print(dic) # 输出结果 {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘, ‘school‘: ‘hashangda‘, ‘male‘: 1}
# 更新字典中的键值对 dic = {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘, ‘school‘: ‘hashangda‘} dic1 = {‘age‘: 23} dic.update(dic1) print(dic) # 输出结果 {‘name‘: ‘szz‘, ‘age‘: 23, ‘addr‘: ‘shanghai‘, ‘school‘: ‘hashangda‘}
# 得到字典所有的值 dic = {‘name‘: ‘szz‘, ‘age‘: ‘18‘, ‘addr‘: ‘shanghai‘, ‘school‘: ‘hashangda‘} values = dic.values() print(values) # 输出结果 dict_values([‘szz‘, ‘18‘, ‘shanghai‘, ‘hashangda‘])
以上是关于python数据类型之内置方法的主要内容,如果未能解决你的问题,请参考以下文章