不同类型的值中包含的属性
查看类型
inta = 12
print(type(inta))
#<class 'int'>
stra = ""
print(type(stra))
#<class 'str'>
lista = []
print(type(lista))
#<class 'list'>
tupa = ()
print(type(tupa))
#<class 'tuple'>
dicta = {}
print(type(dicta))
#<class 'dict'>
查看不同类型的属性dir
-
查看方式
inta = 12 print(dir(inta)) stra = "" print(dir(stra)) lista = [] print(dir(lista)) tupa = () print(dir(tupa)) dicta = {} print(dir(dicta))
属性举例
如数字类型的属性如下
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__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__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
-
可以使用
help()
查看属性的用法print(help(stra.upper)) #去掉属性的括号
属性使用:在不同类型的变量后加**.<属性>
**
-
查看描述
.__doc__
stra = "asd" print(stra.__doc__) #前后双下划线 #运行结果 """ str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'. """
-
查看位长度
.bit_length
inta = 12 print(bin(inta)) #输出0b1100,bin将括号内的转成二进制(0b) print(inta.bit_length()) #输出4(位)
-
大小写
.lower()
小写(str).upper()
大写(str)stra = "Python" print(stra.lower()) #输出python print(stra.upper()) #输出PYTHON
-
切割字符串
.split()
stra = "Python" print(help(stra.split)) print(stra.split("t")) #以t为分隔符,输出['Py', 'hon']
stra = "Python" n = stra.split("t") print(type(n)) #输出结果为<class 'list'>可见分割后的类型为列表
-
输出列表/元组的索引值
list = ["a" , "b" , "c"] print(list.index("b")) #输出结果为1
-
列表后追加元素
<list>.append()
list = ["a" , 3] list.append("b") list.append(6) print(list) #输出结果 ['a', 3, 'b', 6]
元组不可追加,元组中的值不可改变
-
仅列出字典中的键或值
dicta = {"tom" : "123" , "lisa" : "456" , "john" : "789"} print(dicta.keys()) print(dicta.values()) #输出结果 #dict_keys(['tom', 'lisa', 'john']) #dict_values(['123', '456', '789'])