Python基本语法学习总结

来源:互联网 发布:nginx 虚拟主机 编辑:程序博客网 时间:2024/05/17 00:18

List内置方法

List方法方法作用append(x)将x添加到List末尾,相当于a[len(a):]=[x]extend(L)将表L附加到末尾,相当于a[len(a):]=Linsert(i,x)将元素x插入到下标为i的位置remove(x)删除最前面的值为x的元素,若不存在则发生错误pop([i])删除并返回下标为i的元素,若省略参数,则表示弹出最后一个元素index(i)返回第一个值为x的元素的下标,若不存在则发生错误count(x)返回等于x的元素个数sort()将List元素按照非递减排序reverse()将List元素反转

例子:

>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.25), a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]


 

String方法

1 find:返回子串在Sting中第一次出现的index值,没有找到返回-1

>>> title = "Monty Python's Flying Circus"

>>> title.find('Monty')

0

>>> title.find('Python')

6

>>> title.find('Zirquss')

-1

l         可以指定开始查找的位置(包括)和可选的结束位置(不包括)

>>> subject = '$$$ Get rich now!!! $$$'

>>> subject.find('$$$')

0

>>> subject.find('$$$', 1) # Only supplying the start

20

>>> subject.find('!!!')

16

>>> subject.find('!!!', 0, 16) # Supplying start and end

-1

2 join:连接Sequence中的所有元素为一个String,元素必须是String

>>> seq = [1, 2, 3, 4, 5]

>>> '+'.join(seq)

Traceback (most recent call last):

  File "<interactive input>", line 1, in ?

TypeError: sequence item 0: expected string, int found

>>> seq = ['1', '2', '3', '4', '5']

>>> '+'.join(seq)

'1+2+3+4+5'

>>> dirs = '', 'usr', 'bin', 'env'

>>> '/'.join(dirs)

'/usr/bin/env'

>>> print 'C:' + '//'.join(dirs)

C:/usr/bin/env

3 lower:将String转换成小写

>>> 'Trondheim Hammer Dance'.lower()

'trondheim hammer dance'

4 replace:将String中所有出现的某个子串替换成另外一个子串

>>> 'This is a test'.replace('is', 'eez')

'Theez eez a test'

5 split:将String分割成Seqence,不使用分隔符,缺省为空白字符

>>> '1+2+3+4+5'.split('+')

['1', '2', '3', '4', '5']

>>> '/usr/bin/env'.split('/')

['', 'usr', 'bin', 'env']

>>> 'Using the default'.split()

['Using', 'the', 'default']

6 strip:移去String左右的空白字符(缺省)

>>> ' internal whitespace is kept '.strip()

'internal whitespace is kept'


 

 

os和os.path模块
os.listdir(dirname):列出dirname下的目录和文件
os.getcwd():获得当前工作目录
os.curdir:返回但前目录('.')
os.chdir(dirname):改变工作目录到dirname

os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false
os.path.isfile(name):判断name是不是一个文件,不存在name也返回false
os.path.exists(name):判断是否存在文件或目录name
os.path.getsize(name):获得文件大小,如果name是目录返回0L
os.path.abspath(name):获得绝对路径
os.path.normpath(path):规范path字符串形式
os.path.split(name):分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)
os.path.splitext():分离文件名与扩展名
os.path.join(path,name):连接目录与文件名或目录
os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路径

glob
可以使用简单的方法匹配某个目录下的所有子目录或文件,用法也很简单。
glob.glob(regression) 返回一个列表
glob.iglob(regression) 返回一个遍历器

原创粉丝点击