内置函数

1.查看内置函数,进入ipython

In [6]: __builtin__.
Display all 138 possibilities? (y or n)
__builtin__.ArithmeticError            __builtin__.complex
__builtin__.AssertionError             __builtin__.copyright
__builtin__.AttributeError             __builtin__.credits
__builtin__.BaseException              __builtin__.delattr
__builtin__.BufferError                __builtin__.dict
__builtin__.BytesWarning               __builtin__.dir
__builtin__.DeprecationWarning         __builtin__.divmod
__builtin__.EOFError                   __builtin__.dreload
__builtin__.Ellipsis                   __builtin__.enumerate
__builtin__.EnvironmentError           __builtin__.eval
__builtin__.Exception                  __builtin__.execfile
__builtin__.False                      __builtin__.file
__builtin__.FloatingPointError         __builtin__.filter
__builtin__.FutureWarning              __builtin__.float
__builtin__.GeneratorExit              __builtin__.format

2. 常见函数

举例:

  • 取绝对值abs
In [9]: abs(-100)
Out[9]: 100
  • 取最大值、最小值max/min,不能比较字典,因为字典不属于序列
In [15]: min('5214586689990',(1,2),[1,2])
Out[15]: [1, 2]

In [16]: max('5214586689990',(1,2),[1,2])
Out[16]: (1, 2)
  • 取商和余divmod
In [17]: divmod(5,2)
Out[17]: (2, 1)
  • 取次幂pow,如果有第三个参数,再取余
In [18]: pow(5,2)
Out[18]: 25    #5的2次幂

In [19]: pow(5,2,4)    #25除4,余1
Out[19]: 1
  • 取小数点后几位round
In [31]: round(24.45,3)  #保留3位小数,但是目前只有2位小数
Out[31]: 24.45

In [32]: round(24.45,1)
Out[32]: 24.4

In [33]: round(24.45,0)
Out[33]: 24.0

In [34]: round(24.45)      #所以,只有一个参数时,默认输出.0
Out[34]: 24.0
  • 判断可调用,函数、类可被调用
In [35]: a =1

In [36]: callable(a)    a是数字,不可被调用
Out[36]: False

In [37]: def fun():
   ....:     1
   ....:     

In [38]: callable(fun)    #fun是函数,可被调用
Out[38]: True
In [40]: class A(object):    #定义类
    pass
   ....: 
In [41]: callable(A)    #类可被调用
Out[41]: True
  • 判断类型isinstance,比type判断更全面
In [42]: l = [1,2]
In [43]: isinstance(l,list)  #判断l是不是list
Out[43]: True

In [44]: isinstance(l,str) #判断l是不是str
Out[44]: False

In [45]: isinstance(l,(str,list)) #判断l是不是list或者str,只要满足一个就真
Out[45]: True
  • 比较大小
In [46]: cmp(1,1)  #相等输出0
Out[46]: 0

In [47]: cmp(1,2)  #前面的小,输出-1
Out[47]: -1

In [48]: cmp(3,2)    #前面的大,输出1
Out[48]: 1

In [49]: cmp('zell','hello')  #字符串比较不是单纯比较长度
Out[49]: 1
In [50]: cmp('zell','zellp')
Out[50]: -1
  • range和xrange
In [51]: range(3)
Out[51]: [0, 1, 2]

In [52]: xrange(3)
Out[52]: xrange(3)

range直接返回一个列表,真实存在于内存中,占用资源。xrange只有在遍历的时候才返回相应的值,更节省资源。

3. 转换函数

  • int转换整型
In [53]: int('11')
Out[53]: 11

In [54]: int('11.1')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-54-a7a741093b0a> in <module>()
----> 1 int('11.1')

ValueError: invalid literal for int() with base 10: '11.1'

int不能转换带小数点的字符串

  • long转换长整型
  • float转换浮点
  • complex转换复数
  • str转换字符串
  • list转换列表
  • tuple转换元祖
  • hex转换为16进制的字符串,参数为int或者long
In [56]: hex(10)
Out[56]: '0xa'

In [57]: int('0xa')  #int转换字符串不能带引号
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-57-f39cb7e42137> in <module>()
----> 1 int('0xa')

ValueError: invalid literal for int() with base 10: '0xa'

In [58]: int(0xa)
Out[58]: 10
  • eval解析引号里的内容
In [59]: eval('0xa')
Out[59]: 10
In [61]: type(eval('0xa'))
Out[61]: int

再进一步:

In [62]: eval("['1',2]") #如果引号里的内容含引号,注意区分单双引号
Out[62]: ['1', 2]

In [63]: eval('[1,2]')
Out[63]: [1, 2]

In [64]: eval('(1,2)')
Out[64]: (1, 2)

In [65]: eval('{1:2}')
Out[65]: {1: 2}
  • oct转换八进制
  • chr返回int的ASKII码
In [69]: chr(100)
Out[69]: 'd'
  • ord和chr相反,参数是字符,返回int
In [70]: ord('d')
Out[70]: 100

In [71]: ord('\n')
Out[71]: 10

4. 字符串处理方法

In [72]: s = 'hello'

In [73]: s.
s.capitalize  s.expandtabs  s.isdigit     s.ljust       s.rindex      s.splitlines  s.upper
s.center      s.find        s.islower     s.lower       s.rjust       s.startswith  s.zfill
s.count       s.format      s.isspace     s.lstrip      s.rpartition  s.strip       
s.decode      s.index       s.istitle     s.partition   s.rsplit      s.swapcase    
s.encode      s.isalnum     s.isupper     s.replace     s.rstrip      s.title       
s.endswith    s.isalpha     s.join        s.rfind       s.split       s.translate   

以上是字符串的全部内置方法

  • .capitalize将首个字母大写
In [74]: s.capitalize()
Out[74]: 'Hello'
  • .replace('待替换',‘替换值’,换几个)替换
In [75]: s.replace('H','h')  #替换第一个H
Out[75]: 'hello'

In [78]: .replace('l','L',1)  #替换第一个l
Out[78]: 'heLlo'

In [76]: .replace('l','L',2)  #替换2个l
Out[76]: 'heLLo'
  • .split切断字符串,返回列表。默认分隔符是空格
In [81]: s = 'hello h'

In [82]: s.split()
Out[82]: ['hello', 'h']

指定分隔符、切几个

In [84]: s ='192.168.1.1'

In [85]: s.split('.',1)    #切1个
Out[85]: ['192', '168.1.1']

In [87]: s.split('.',2)  #切2个
Out[87]: ['192', '168', '1.1']

In [88]: s.split('.')  #不写切几个,默认全切
Out[88]: ['192', '168', '1', '1']
  • .join(序列)连接序列里的元素,返回字符串
In [89]: '+'.join([11,2])  #列表里的元素得是字符串,不然报错
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-7387fe37ff7d> in <module>()
----> 1 '+'.join([11,2])

TypeError: sequence item 0: expected string, int found

In [90]: '+'.join(['11','2'])  #+连接
Out[90]: '11+2'
In [91]: ''.join(['11','2'])  #连接符不写
Out[91]: '112'

In [92]: ' '.join(['11','2'])  #连接符是空格
Out[92]: '11 2'

把列表换成元祖,和列表一样,元素得是字符串

In [93]: ' '.join(('11','2'))
Out[93]: '11 2'
  • string模块
In [95]: import string

In [96]: string.
string.Formatter        string.capwords         string.ljust            string.rsplit
string.Template         string.center           string.lower            string.rstrip
string.ascii_letters    string.count            string.lowercase        string.split
string.ascii_lowercase  string.digits           string.lstrip           string.splitfields
string.ascii_uppercase  string.expandtabs       string.maketrans        string.strip
string.atof             string.find             string.octdigits        string.swapcase
string.atof_error       string.hexdigits        string.printable        string.translate
string.atoi             string.index            string.punctuation      string.upper
string.atoi_error       string.index_error      string.replace          string.uppercase
string.atol             string.join             string.rfind            string.whitespace
string.atol_error       string.joinfields       string.rindex           string.zfill
string.capitalize       string.letters          string.rjust            
In [96]: string.lowercase
Out[96]: 'abcdefghijklmnopqrstuvwxyz'
In [97]: string.uppercase
Out[97]: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

string.replace对比s.replace

In [98]: string.replace('hello','h','H')
Out[98]: 'Hello'

推荐阅读更多精彩内容