python语法笔记

Python 是一种面向对象、解释式编程语言。与 Scheme、Ruby、Perl、Tcl 等动态语言一样,Python具备垃圾回收功能,能够自动管理内存使用。它经常被当作脚本语言用于处理系统管理任务和网络程序编写,然而它也非常适合完成各种高级任务。

一. python 源文件通常使用后缀名 .py,在shell命令行使用
python filename.py arguments
执行python程序。

二. 每一个 python 源文件(filename.py)称为一个模块,进行导入声明后,可以在其它程序中使用。导入方式是在程序最开始部分进行声明。
import filename
python标准库提供了三个常用的模块。
(1) sys --提供exit(), argv, stdin, stdout等方法和内置变量;
(2) re --提供正则表达式相关的方法和内置变量;
(3) os --提供系统接口函数,文件系统操作接口等。

三. python 的内建字符串类名是 str,引用字符串常量时常使用单引号。
astr  = ‘hello, world ’
pi  =  3.14
## print  astr + pi   ## syntax error
print  astr + str(pi)
执行上面三条命令后,将打印
hello, world 3.14
通过本例,说明以下几个方面。
(1) 引用字符串常量时常使用单引号。
(2) 每一行的结束代表一条语句的结束,不需用分号。
(3) 使用 +不会自动将数字自动转换为字符串,需要使用str将数字转为字符串(返回值是字符串,不影响数字本身),避免出现语法错误。
(4) 使用 #表示注释行。另外在定义函数时,使用"""docment""",即三个双引号来为函数添加说明注释。这样的注释必须位于定义函数的冒号后最开始的行。
为字符串变量赋值时,如果在常量字符串前加上 r字母,则表示后面的字符串是纯义字符串(raw string),即赋值时不识别转义字符,只当作普通字符处理。
raw  = r‘this\t\n and that ’
字符串中的 \t或 \n 都被当作字符串本身处理。
python常用的内置字符串函数:
(1) str.lower(), str.upper() –返回转换大小写后的字符串;
(2) str.strip() --返回删除字符串开头和结尾空白字符后的字符串;
(3) str.isalpha(),str.isdigit(), str.isspace()… --判断是否所有字符都是字母,数字或空白等等;
(4) str.startswith(‘string’),str.endswith(‘string’) –判断给定字符串是否以参数开头或结尾;
(5) str.find(‘srch’) –返回给定字符串中首次出现参数字符串(不支持正则表达式)的位置,如果没找到则返回-1;
(6) str.replace(‘oldstr’, ‘newstr’) –返回将给定字符串中所有oldstr替换成newstr后的结果字符串;
(7) str.split(‘delim’) –将给定字符串以参数(不支持正则表达式)为分割符进行分割,返回分割后的list类型结果;
(8) str.join(list) –和split相反,该函数将list类型中各字符串元素连接成一个字符串并返回。
python可利用下标访问字符串的片段。
astr  = ‘hello ’
print astr[1:4]    ## refer to ‘ell’
print astr[1:]    ## refer to ‘ello’
print astr[:]    ## refer to ‘hello’
print astr[1:100]    ## refer to ‘hello’
另外,可以利用负数倒序访问字符串中的元素或片段,字符串最后一个字符的下标是 -1,倒数第二字符下标为 -2,然后依次减小直到第一个字符。
格式化字符时,使用 % 运算符。
# % operator
astr = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')

四. python 不用 {} 来标志 if/loops/function 块儿,而是用冒号(:)来起始一个块,而之后缩进一致的行都被视为在该块中,直到缩进更改的行。一个缩进一般使用四个空格,不能使用TAB键。另外,布尔判断语句不需要由括号包围。
if speed >= 80:
    print 'License and registration please'
    if mood == 'terrible' or speed >= 100:
        print 'You have the right to remain silent.'
     elif mood == 'bad' or speed >= 90:
        print "I'm going to have to write you a ticket."
        write_ticket()
     else:
         print "Let's try to keep it under 80 ok?"

五. python内建链表(数组)类名为list。使用中括号定义和赋值,使用下标引用。
colors  = [‘red’, ‘blue’, ‘green’]
print   colors[2]      ## green
colors[0:-1]  =  ‘purple’    ## colors  = [‘purple’, ‘green’]
hues = colors     ## will not copy the list, hues and colors point to the same memory address
del hues ## will remove the definition of hues, but colors will not be affected
tints = colors[:]  ## will make a copy for tints
print   len(colors)    ## 3
使用下标时和 str 类的下标方式类似。但是可以利用下标访问并对链表元素值进行修改操作,这是字符串不具备的功能。
将链表名赋值给另一个变量时,并不进行复制操作,而是将另一个变量同时执行链表在内存中的地址。但使用 del 删除其中一个变量时,并不影响另外一个,类似 linux 的软连接。
对链表进行加法运算(+)时,将合并链表成一个链表,运算符右端的链表中的元素成为新链表下标较大的元素。
对链表使用for var in list:进行遍历访问十分方便,但不能在循环过程中添加或删除链表元素。但是可以利用特定的方式利用 for in 生成一个新的链表。
fruits = ['apple', 'cherry', 'bannana', 'lemon']
afruits = [ s.upper() for s in fruits if 'a' in s ] ## afruits = [‘APPLE’, ‘BANNANA’]
另外 var in list 的形式也可以作为布尔判断语句。
range(n) 生成一个 0, 1, … n-1 的链表数列,range(a, b) 生成一个 a, a+1, … b-1的链表数列。
也可以使用 while 循环遍历链表,同时可使用 break 和 continue 进行循环控制。
while  i<len(list):
        print list[i]
        i+=1 ## i=i+1, python does not has ++ or  --  operator 
list 常用的内置函数:
(1) list.append(elmt) –在原list的后面添加一个元素elmt,不返回任何值;
(2) list.insert(index, elmt) –在指定的index的处添加元素,原元素后移;
(3) list.extend(list2) –将list2添加到原list后,和加法运算类似;
(4) list.index(elmt) –查找链表中第一个elmt的位置(index)并返回index,如果找不到,产生 ValueError错误;
(5) list.remove(elmt) –查找链表中第一个elmt的位置(index)并删除elmt,如果找不到,产生 ValueError错误;
(6) list.sort() –将链表排序,不返回任何值。现在最好使用sorted()函数进行该操作;
(7) list.reverse() –反转链表,不返回任何值;
(8) list.pop(index) –返回index指向的元素,并从链表中将其删除。如果省略index参数,则对最后一个元素进行上述操作;
(9) ‘delim’.join (list) –将链表元素以delim为间隔符连接成一个字符串并返回;
(10) str.split(‘delim’) –将str以delim为分割符,分割成一个链表并返回。

六. tuple 是一种类似坐标的结构。使用小括号定义并赋值于变量,可使用下标访问,但不能使用下标对元素赋值,及tuple实际上是不可变的结构。
tuple1  = (‘red’, ‘blue’, ‘green’)
print tuple1[0]  ## print red   
## tuple1[0]  = ‘purple’ 语法错误,不能更改tuple元素值
tuple1  = (1,  2,  ‘color’)   ## 重新为tuple1变量赋值

七. 内置排序函数的原型是sorted(iterable, cmp=None, key=None, reverse=False),该函数返回排序后的可排序对象,但对原参数对象不作修改。
iterable–可遍历排序的对象,可以是链表,也可以其它对象;
cmp–比较函数,一般该函数带两个参数,函数体根据自定义规则比较两个参数大小,返回负数、零或正数,分别代表第一个参数小于第二个参数,两参数相等和第一个参数大于第二个参数,sorted函数根据该比较函数对对象排序;
key–比较目标指定函数,一般该函数带一个参数,返回从该参数中指定的比较目标。例如:
strs = ['ccc', 'aaaa', 'd', 'bb']
print sorted(strs,  key=len)   ## ['d', 'bb', 'ccc', 'aaaa']
sorted 遍历strs链表,并将每一个元素交给len()函数测定其长度,然后按个元素的长度排序;
reverse – 是否倒序排列,False为否,True为真。

八. python 提供内置的 Hash 表类名为dict。dict 的使用方法如下。
dict = {}
dict[key_1] = value_1   
dict[key_2] = value_2
print dict[key_1]  ## value_1
print dict    ## {key_1:value_1,  key_2:value_2}
del dict[key_1]  ## remove the key_1:value_1 pair from the dict
dict 对象就是用大括号括起来的一些 键:值 列表。 一个 dict 的每个 key 都是唯一的,可以重复赋值,后面的赋值将覆盖前面的。一般来说,key 是不可以更改的,因此可以python 中的字符串对象,数值对象和元组对象作为 key,而值则可以是任何类型的对象。
通过中括号引用key可以访问值。但如果 key 实际上不存在 dict 中,将会抛出 KeyError 错误。为了避免错误,可以使用 key in dict 的形式对 key 是否存在表中做判断(返回True或False),或使用内置函数 dict.get(key) 的形式访问。
可以利用for循环遍历dict的键,进而可以遍历 dict 的值。
for key in dict: print key  ## print each key in random order
for key in sorted(dict.keys()):  print key, dict[key]  ## print key and value pairs in ascending order of keys
for k, v in dict.items():  print key ‘>’ v  ## print key and value pairs 
dict常用的内置函数:
(1) dict.get(key, default=None) – 返回key对应的值,如果key不在dict中,则返回None(不抛出KeyError错误);
(2) dict.clear() – 清空dict所有元素;
(3) dict.copy() – 将返回dict的一个软拷贝;
(4) dict.fromkeys(keys[, values]) – 以keys(链表)和values(链表)为 键-值 创建新的dict并返回;
(5) dict.has_key(key) – 判读key是否在dict中,如果存在则返回True,否则返回False,相当于key in dict判断;
(6) dict.items() – 将dict的每个键值对转换为tuple,并依次加入链表,完成后返回链表;
(7) dict.keys() – 返回由dict所有键构成的链表;
(8) dict.values() – 返回由dict所有值构成的链表 ;
(9) dict.setdefault(key, default=None) – 返回key对应的值,如果key不在dict中,则返回default参数对应的值;
(10) dict.updae(dict2) – 将dict2中的所有键值对复制加入到dict中,不返回值。

九. python中提供了一些对文件进行读写操作的内置函数。
import codecs
import os
hwnd = open(‘filename.txt’, ‘w+U’, ‘utf-8’) ## open the file and returns the file handle
## parameter ‘r’ for reading, ‘w’ for writing, and ‘a’ for append. ‘b’ for binary mode, ‘+’ for updating, ‘U’ for 
## converting different line-ending characters so they always come through as a simple ‘\n’
## uses codecs lib, sets the string encoding method
for line in hwnd: print line   ## iterates over the lines of the file ## use ‘print line,’ to avoid extra blank lines
lines = hwnd.readlines()   ## lines will be a list which take each line (including the \n) as its elements
text = hwnd.read([cnt])   ## read hwnd as a text field, the optional argument cnt specifies how many bytes of 
## data is are to be read
hwnd.write(‘write texts to file hwnd.\n’)   ## overwrites the existing file if the file exist, or create a new file and ## write the contents to it.
pos = hwnd.tell()   ## returns current read/write position of the file
hwnd.seek(1, 0)   ## relocate the read/write position to the second line
hwnd.close()   ## close the file
os.rename(old_file_name, new_file_name)   ## rename files
os.remove (file_name)   ## delete a file
os.mkdir (‘newdir’)   ## create a new directory under current path
os.chdir (‘newdir’)   ## change the current directory 
os.getcwd ()   ## get the current working path
os.rmdir (‘dirname’)   ## delete the directory, but all contents in the folder must be removed in advance
os.listdir (‘path’)   ## return a list which has the file names (not path) as its elements.

十. python正则表达式功能由标准库中的re模块提供。最常用的用法如下。
match = re.search(pat, str)   
serach 函数第一个参数 pat 是待查找的内容,可以是简单的字符串,也可以是正则表达式。pat 写为正则表达式时,为了避免将字符串中的正则表达式元字符(例如 \w, \b等)解释为转义字符,应为其加上 r 前缀。并且,可以使用小括号对查找内容进行分组,以便之后引用。例如
match = re.search(r'(\d\d\d)(\w)', 'p123g')   ## match three continuous decimal digits
print ‘found’, match.group()   ## group function returns the found texts: 123g
print ‘found’, match.group(1)   ## returns the first group of the found texts: 123
print ‘found’, match.group(2)   ## returns the second group of the found texts: g
serach 函数第二个参数 str 是查找 pat 的字符串。
如果str中存在匹配 pat 的内容,该函数将返回一个match对象;否则如果未找到匹配内容,则返回None。因此可以使用if语句跟在search函数后,判断查找结果后进行下一步操作。
search 函数是非贪婪的,即它只匹配第一个匹配pat的内容便返回,而无视后面是否能继续匹配。re模块中的另一个函数
re.findall(pat,str)
则是贪婪的,它会匹配所有的匹配内容,并将每一个匹配到的对象放入链表,查找完成后返回链表。并且,如果在 findall 函数中对 pat 进行分组,则它会将每一个匹配对象以pat分组分割后,生成一个 tuple 后再放入链表中,这时,不在分组中的部分将不会出现在 tuple 里。
除了以上两个查找函数外,re模块还提供了正则替换函数
re.sub(pat, replacement, str)
该函数将 pat 替换成 relacement 后的 str。如果对 pat 进行分组,则可在relacement中使用 \1, \2 等对应 group(1), group(2) 等。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值