9.1 12个内建函数
-
abs函数:返回一个数字的绝对值
-
>>> print(abs(-10)) 10
bool函数:根据这个参数的值返回真假
-
>>> print(abs(-10)) 10 >>> print(bool(1)) True >>> print(bool(None)) False >>> print(bool('a')) True
bool函数对于空的列表,元组和字典返回False,否则就返回True
-
>>> my_sily_list = [] >>> print(bool(my_sily_list)) False >>> my_sily_list = ['s','i','l','y'] >>> print(bool(my_sily_list)) True
例子分析:
- 第一行使用input函数把输入保存到变量year中(不包括Year of birth),(回车键也会保存到变量中)
- rstrip函数:把字符串结尾的空白和回车删除
- not关键字:如果函数没有返回True的话才做这件事
-
>>> year = input('Year of birth') Year of birth >>> if not bool(year.rstrip()): print('You need to enter a value for your year of birth') You need to enter a value for your year of birth
dir函数:可以返回任何值的相关信息,显示对一个列表值可用的函数(可以作用于字符串,数字,函数,模块,对象,类)
-
>>> dir(['a','short','list']) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__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']
快速查找一个变量可以做什么
-
>>> dir(pop) ['__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', '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']