对函数有了一定了解之后,我们来看看Python的内置函数。下图是Python所有的内置函数,共68个。

详细介绍:https://docs.python.org/3/library/functions.html 

 

这么多的内置函数,我们怎么学习呢?

我把他们分成几类,咱们由易到难的来学习一下。

先来看第一类,我们相对比较熟悉的。

1.print   # 打印一些值,默认是输出到标准输出

>>> help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

file参数可以控制输出流到别的位置。
sep参数用于控制分割符,默认是空格。

end参数控制字符串输出后是否自动加'\n',你可以改为别的。
flush参数控制是否强制刷新流。

eg.

>>> a = 'Hello'
>>> b = 'Python'
>>> print(a,b)
Hello Python
>>> print(a,b,sep='  |  ',end=' !\n')
Hello  |  Python !

 看到区别了吧。

 

2.abs # 返回数字的绝对值

>>> help(abs)
Help on built-in function abs in module builtins:

abs(x, /)
    Return the absolute value of the argument.

没什么好说的,看例子吧

>>> a = 10
>>> b = -10
>>> print(abs(a),abs(b))
10 10

 abs只能操作数字,字符串是不可以的。

>>> a='xxx'
>>> abs(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'

3.input # 从标准输入接收一个字符串

>>> help(input)
Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.

    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.

    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.

prompt参数可接收一个字符串,并输出到标准输出在读取输入的前面

如果用户输入(Linux: Ctrl-D, Windows: Ctrl-Z+Return),会抛出一个异常

eg.

>>> input('What is your name?')
What is your name?Python
'Python'
>>> name = input('What is your name?')
What is your name?World
>>> print(name)
World
>>> name = input('What is your name?')
What is your name?Traceback (most recent call last):   # 此处按了Ctrl-c
  File "<stdin>", line 1, in <module>
KeyboardInterrupt
>>> name = input('What is your name?')
What is your name?^D    # # 此处按了Ctrl-d+Return

input函数接收的任何输入都会以字符串形式存储。

4.type  # 得到一个返回值,从而知道想要查询的对像类型信息。

>>> a = 'xxxx'
>>> type(a)
<class 'str'>
>>> b = 123
>>> type(b)
<class 'int'>

 5.int # 将数字转化为整型

>>> help(int)
Help on class int in module builtins:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 |
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.

eg.

>>> a = input('Input a number:') # 还记得input接收的是个字符串吧?
Input a number:23
>>> type(a)
<class 'str'>
>>> int(a)
23
>>> type(int(a)) # 把字符串转化成了整型
<class 'int'>

 上面是最基本的用法。

>>> int()    # 当括号里什么都不输入的时候,返回一个整型的“0”
0
>>> type(int())
<class 'int'>

 

>>> a=9.99999  
>>> int(a)  #对浮点型数字做使用int函数,返回整数部分
9

 int有个base参数,表示前面参数值按照几进制转化十进制,默认为10,因为我们用的最多的就是十进制数字。而int最终返回的结果都是十进制整型数字。

>>> int('100010',2)  # base参数是2,表示'100010'是二进制的
34
>>> int('0xa',16)      # base参数是16,表示'0xa' 是十六进制的
10
>>> int(100010,2)    # 第一个参数必须是字符串!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() can't convert non-string with explicit base

 base 的 可选值包括0和2-36中的任意一个.  如果base为0的时候它将会猜测这个字符串的内容进行转换。

>>> int('101',0)  # 猜测‘101’是十进制
101 
>>> int('0xa',0)  # 猜测‘0xa’是十六进制
10
>>> int('0xa',10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0xa'

 6.str  # 将对象转化为字符串

def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
"""
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'.
# (copied from class doc)

eg.

>>> x = 123
>>> print(type(x))
<class 'int'>
>>> print(str(x))
123
>>> print(type(str(x)))
<class 'str'>
>>> hello = 'hello, world\n'
>>> a = str(hello)
>>> print(a)
hello, world

 

>>> h = [1,2,3,4]
>>> print(type(h))
<class 'list'>
>>> a = str(h)
>>> print(a)
[1, 2, 3, 4]
>>> print(type(a))
<class 'str'>

  我们更多是将数字转为字符串。

7.repr # 和str()很类似,repr()是将一个对象转成字符串显示,注意只是显示用,有些对象转成字符串没有直接的意思。

  str()函数得到的字符串可读性好(故被print调用)

  repr()函数得到的字符串通常可以用来重新获得该对象,通常情况下 obj==eval(repr(obj)) 这个等式是成立的。这两个函数接受一个对象作为其参数,返回适当的字符串。(eval函数后面会提)

eg.

>>> x = 'hello !\n'
>>> print(str(x))
hello !

>>> print(repr(x))
'hello !\n'

 str()的输出是友好的,像是给人看的;而repr()的输出更像是给python看的。

 另:python3.5中不支持反引号``

8.list #将对象转为列表

>>> help(list)
Help on class list in module builtins:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items

eg.

>>> a = '123'
>>> type(a)
<class 'str'>
>>> b = list(a)
>>> type(b)
<class 'list'>
>>> print(b)
['1', '2', '3']
>>> a = "[1,2,3]"
>>> b = list(a)
>>> print(b)
['[', '1', ',', '2', ',', '3', ']']

 9.tuple #将对象转为元组,跟list函数类似

class tuple(object)
 |  tuple() -> empty tuple
 |  tuple(iterable) -> tuple initialized from iterable's items
 |
 |  If the argument is a tuple, the return value is the same object.

eg.

>>> a="123"
>>> b=tuple(a)
>>> print(b)
('1', '2', '3')

10.dict #从可迭代对象来创建新字典

>>> help(dict)
Help on class dict in module builtins:

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)

eg.

#以键对方式构造字典
>>> d1 = dict(one = 1, two = 2, a = 3)
>>> print(d1)
{'a': 3, 'one': 1, 'two': 2}
#以映射函数方式来构造字典
>>> d2 = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> print(d2)
{'one': 1, 'two': 2, 'three': 3}
#可迭代对象方式来构造字典
>>> d3 = dict([('one', 1), ('two', 2), ('three', 3)])
>>> print(d3)
{'one': 1, 'two': 2, 'three': 3}
>>> d4 = dict(d3)
>>> print(d4)
{'one': 1, 'two': 2, 'three': 3}

 zip函数后面会提到。

11.sum #求和

>>> help(sum)
Help on built-in function sum in module builtins:

sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

本函数用来计算可迭代对象iterable的和,然后以这个结果再加上start的值。

参数start用来指定相加的参数,如果没有设置这个值,默认是0 值。

要计算和的序列一般是数字类型,并且开始参数要设置为数字类型。

其它有些情况之下,使用别的计算和的方式会更好,

比如计算字符串的和使 用’’.join(sequence);或者计算浮点数的和使用math.fsum();或者计算多序列的和使用itertools.chain()。

eg.

>>> print(sum([2, 5, 8], 1))
16

 # 了解一下 “x for x in y” 写法,y是可迭代对象(字符串,列表等),通过for循环取出y中每个元素赋值给x

>>> print(sum((int(v) for v in '123'),20))
26

 

12.max # 返回其参数最大值:最接近正无穷大的值。

>>> help(max)
Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value

    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.

eg.

>>> print("max(80, 100, 1000) : ", max(80, 100, 1000))
max(80, 100, 1000) :  1000
>>> print("max(-20, 100, 400) : ", max(-20, 100, 400))
max(-20, 100, 400) :  400

 字符串和列表也是可以比较的,你也可以尝试一下别的数据类型

>>> max('a','b')
'b'
>>> max([1,2],[2,3])
[2, 3]
>>> max([1,2],[1,2,3])
[1, 2, 3]

 13.min #返回其参数最小值:最接近负无穷大的值。类似max

>>> help(min)
Help on built-in function min in module builtins:

min(...)
    min(iterable, *[, default=obj, key=func]) -> value
    min(arg1, arg2, *args, *[, key=func]) -> value

    With a single iterable argument, return its smallest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the smallest argument.

eg.

>>> print("min(-20, 100, 400) : ", min(-20, 100, 400))
min(-20, 100, 400) :  -20

 14.float # 将对象转为浮点型数字

>>> help(float)
Help on class float in module builtins:

class float(object)
 |  float(x) -> floating point number
 |
 |  Convert a string or number to a floating point number, if possible.

eg.

>>> a='123.45'
>>> b=float(a)
>>> print(b)
123.45
>>> c='10'
>>> print(float(c))
10.0
>>> d=5
>>> print(float(d))
5.0

 15.help #查看对象的帮助信息

用了这么多次,不陌生了吧

>>> help(help)
Help on _Helper in module _sitebuiltins object:

class _Helper(builtins.object)
 |  Define the builtin 'help'.
 |
 |  This is a wrapper around pydoc.help that provides a helpful message
 |  when 'help' is typed at the Python interactive prompt.
 |
 |  Calling help() at the Python prompt starts an interactive help session.
 |  Calling help(thing) prints help for the python object 'thing'.

单独执行help()

>>> help()

Welcome to Python 3.5's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

 16.len  # 返回对象长度(按字符,不是字节)

>>> help(len)
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

>>> a='xxxxd'
>>> print(len(a))
5
>>> b='你好,世界!'
>>> print(len(b))
6

 17.pow  # 求指数,可取模

>>> help(pow)
Help on built-in function pow in module builtins:

pow(x, y, z=None, /)
    Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

    Some types, such as ints, are able to use a more efficient algorithm when
    invoked using the three argument form.

eg.

>>> pow(3,4)  #3**4,3的4次方
81
>>> pow(3,4,2)  #3**4%2 3的4次方对2取模
1

>>> pow(2,4)
16
>>> pow(2,4,6)
4
>>> pow(2,4,7)
2

 18.range # 返回一个组数字

>>> help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |
 |  Return an object that produces a sequence of integers from start (inclusive)
 |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 |  These are exactly the valid indices for a list of 4 elements.
 |  When step is given, it specifies the increment (or decrement).

eg.

>>> print([i for i in range(10)])     # 默认起始值为0
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print([i for i in range(3,10)])   # 指定起始值
[3, 4, 5, 6, 7, 8, 9]
>>> print([i for i in range(3,10,3)]) #指定步长值,如果指定步长值,必须指定起始值
[3, 6, 9]
>>> for i in range(0,10,2):             #更多的用法是用来控制循环次数
...     print(i)
...
0
2
4
6
8

 19.round # 四舍五入,保留n位小数,默认是0

>>> help(round)
Help on built-in function round in module builtins:

round(...)
    round(number[, ndigits]) -> number

    Round a number to a given precision in decimal digits (default 0 digits).
    This returns an int when called with one argument, otherwise the
    same type as the number. ndigits may be negative.

eg.

>>> round(9.5)
10
>>> round(9.4)
9
>>> round()      #必须传参数
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Required argument 'number' (pos 1) not found

>>> float(round(2.9994569,4))  
2.9995
>>> float(round(2.9994569,5))
2.99946

 20. sorted #对一个可迭代的对象进行排序

>>> help(sorted)
Help on built-in function sorted in module builtins:

sorted(iterable, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.

    A custom key function can be supplied to customise the sort order, and the
    reverse flag can be set to request the result in descending order.

eg.

>>> list=[3,2,4,5,1]
>>> sorted(list)
[1, 2, 3, 4, 5]
>>> sorted(list,reverse=True)  # reverse表示反转
[5, 4, 3, 2, 1]

 参数key也是接受一个函数,不同的是,这个函数只接受一个元素

>>> L = [{1:5,3:4},{1:3,6:3},{1:1,2:4,5:6},{1:9}]
>>> def f(x):
...     return len(x)
...
>>> lo=sorted(L,key=f)
>>> lt=sorted(L,key=f,reverse=True)  
>>> print(lo)
[{1: 9}, {1: 5, 3: 4}, {1: 3, 6: 3}, {1: 1, 2: 4, 5: 6}]
>>> print(lt)
[{1: 1, 2: 4, 5: 6}, {1: 5, 3: 4}, {1: 3, 6: 3}, {1: 9}]

 21.reversed  # 返回序列seq的反向访问的迭代子

>>> help(reversed)
Help on class reversed in module builtins:

class reversed(object)
 |  reversed(sequence) -> reverse iterator over values of the sequence
 |
 |  Return a reverse iterator

eg.

>>> for i in reversed([2, 3, 4, 5]):
...     print(i, end = ',')
...
5,4,3,2,>>>
>>> print(reversed([2, 3, 4, 5]))    # 此输出报错
<list_reverseiterator object at 0x0059EFB0>