目 录 第一章 Python 基础 ..................................................................................................... 2 1.1 符号 .................................................................................................................................... 2 1.2 python 关键字: ................................................................................................................ 5 第二章 Python Functions ......................................................................................... 7 2.1 math: ................................................................................................................................ 7 2.2 random: ........................................................................................................................... 8 2.3 dir()存储命名空间 ........................................................................................................ 8 2.4 全局变量与局部变量: .................................................................................................... 9 2.5 递归调用: ...................................................................................................................... 10 第三章 Lists, Tuples and Dictionaries ...................................................................... 12 3.1 Lists, Tuples...................................................................................................................... 12 3.2 Dictionary ......................................................................................................................... 13 3.3 二维数组 .......................................................................................................................... 16 第四章 Common Gateway Interface (CGI) 公共网关接口简介 ............................ 18 4.1 服务模式 .......................................................................................................................... 18 4.1.1 显示时间............................................................................................................................... 18 4.1.2 文本格式化........................................................................................................................... 19 4.1.3 查询..................................................................................................................................... 20 4.1.4 输入框及按钮..................................................................................................................... 21 4.1.5 登陆校验.............................................................................................................................. 22 第五章 面向对象编程 ............................................................................................... 23 第六章 用户自定义类 ............................................................................................... 29 6.1 自定义的字符串表示方法: __str__ ........................................................................... 29 6.2 自定义属性访问 .............................................................................................................. 29 6.3 重载二元运算符 .............................................................................................................. 31 6.4 类型之间的转换 .............................................................................................................. 32 第一章 Python 基础 python 可进入 python 模式 >>>import re 导出 re >>>dir(re) 查看 re 中的函数、属性等 >>>help(compile) 查看 re 中 compile 的描述 vim /root/.vimrc set tabstep=4 按 Tab 空 4 格 vim a #!/bin/python print 换行 1.1 符号 print "\n" 换行 \b 空格 \t 光标移至下一个 tab 单位 \r 光标移至行首 \a 报警,系统铃声 \\ \ \” ” \’ ’ integer1 = raw_input( "Enter first integer:\n" ) #从键盘读取初始类别为 string,raw_input() 为读取键盘输入的函数 print "integer1: ", id( integer1 ), type( integer1 ), integer1 integer1 = int( integer1 ) # 转换成 integer 类型 print "integer1: ", id( integer1 ), type( integer1 ), integer1 integer2 = raw_input( "Enter second integer:\n" ) print "integer2: ", id( integer2 ), type( integer2 ), integer2 integer2 = int( integer2 ) print "integer2: ", id( integer2 ), type( integer2 ), integer2 sum = integer1 + integer2 # 求和 print "sum: ", id( sum ), type( sum ), sum integerValue = 4237 print "Integer 4237 print "Decimal integer %d" % integerValue 4237 ", integerValue 内 外 都 需 % , %d print "Hexadecimal integer %x\n" % integerValue 108d print "Force eight digits in integer %.8d" % integerValue 00004237 print "Right justify integer (%8d)" % integerValue ____4237 print "Left justify integer (%-8d)\n" % integerValue 4237____ floatValue = 123456.789 print "Float", floatValue print "Default float %f" % floatValue print "Default exponential %e\n" % floatValue print "Five digits after decimal in float %.5f" % floatValue 123456.78900 %x %.8d 强制 8 位,少了用 0 补 %8d 从 右 至 左 8 位 %-8d 从 左 至 右 8 位 123456.789 %f 123456.789000 %e 1.234568e+05 %.5f 保留到小数点后 5 位 stringValue = "String formatting" print "Fifteen and five characters allowed in string:" print "(%.15s) (%.5s)" % ( stringValue, stringValue ) %.15s 保留 15 位长度 %.5s 保留 5 位长度(String formatti) (Strin) number1 = raw_input( "Please enter first integer: " ) number1 = int( number1 ) number2 = raw_input( "Please enter second integer: " ) number2 = int( number2 ) if number1 == number2: print "%d is equal to %d" % ( number1, number2 ) else: print "%d is not equal to %d" % ( number1, number2 ) 运算符号: Addition Subtraction Multiplication Exponentiation Division Modulus 括号 符号 + – * ** / // % () += -= *= **= /= 现实符 f+7 p–c bm xy x ÷ y or x / y r mod s c+=7 d-=4 e*= 5 f **= 3 g /= 3 python f+7 p–c b*m x ** y x/y x // y r%s c=c+7 d=d-4 e=e*5 f = f ** 3 g=g/3 if,else 后都接 : 优先级(越小越高) 4 4 3 2 3 3 3 1 %= h %= 9 h=h%9 例: y = 2 * 5 ** 2 + 3 * 5 + 7 y=72 例: 3.0/4.0=0.75 3/4=0 当运行 from __future__ import division 后 3/4=0.75 3.0/4.0=0.75 判断符号: == 判断等于 !=,<> 判断不等于 < 判断小于 > 判断大于 >= 判断大于等于 <= 判断小于等于 3.0//4.0=0.0 优先级 6 6 5 5 5 5 total = 0 # sum of grades gradeCounter = 1 # number of grades entered while gradeCounter <= 10: # loop 10 times grade = raw_input( "Enter grade: " ) # get one grade grade = int( grade ) total = total + grade gradeCounter = gradeCounter + 1 average = total / 10 print "Class average is", average %c %s %d %u %o %x %X letters). %f %e,E %g,G while 循环 单字符 char 字符串 string Signed decimal integer. Unsigned decimal integer Unsigned octal integer. Unsigned hexadecimal integer (with hexadecimal digits a through f in lowercase letters). Unsigned hexadecimal integer (with hexadecimal digits A through F in uppercase Floating-point number. Floating-point number (using scientific notation). Floating-point number (using least-significant digits) 150.4582=1.504582*102=1.504582E+002 python a 3//4=0 运行 \ 为转义字符 比如双引号写成 \" print 函数后可接单引号也可接双引号 print 'abc' 等同于 print "abc" 1.2 python 关键字: and continue else assert def except break del exec class elif finally if…else…: if grade >= 90: print "A" else: if grade >= 80: print "B" else: if grade >= 70: print "C" else: if grade >= 60: print "D" else: print "F" 等同于: if grade >= 90: print "A" elif grade >= 80: print "B" elif grade >= 70: print "C" elif grade >= 60: print "D" else: print "F" for import not raise from in or return global is pass try if lambda print while 算出成绩的平均分: total = 0 # sum of grades gradeCounter = 0 # number of grades entered # processing phase grade = raw_input( "Enter grade, -1 to end: " ) # get one grade grade = int( grade ) # convert string to an integer while grade != -1: total = total + grade gradeCounter = gradeCounter + 1 grade = raw_input( "Enter grade, -1 to end: " ) grade = int( grade ) # termination phase 缩进结束了代表 while 循环结束 if gradeCounter != 0: average = float( total ) / gradeCounter print "Class average is", average else: print "No grades were entered" 显示: Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82.5 range(a,b,c) a 为起始 b 为终结 c 为公差,可正可负 range(10) 得到:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 从 0 到 10 range(0,10,1) 得到:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(0,10,2) 得到:[0, 2, 4, 6, 8] range(1,2) 得到:[1] 从 1 到 2 range(1,1) 得到:[] 从 1 到 1 为空 range(10,0,-1)得到:[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 求 100 内偶数和: sum = 0 for number in range( 2, 101, 2 ): sum += number print "Sum is", sum 输出跳过 5: for x in range( 1, 11 ): if x == 5: continue print x for 。 。。 in 。。 。 跳过,进入下一个循环 第二章 Python Functions 通过 import 导入模块来调用模块中的函数等: 2.1 math: import math print math.sqrt( 900 ) 求 900 的方差,得到 30 math 模块的方法,使用前 import math 方法 描述 例子 acos( x ) Trigonometric arc cosine of x (result in radians) acos( 1.0 ) = 0.0 asin( x ) Trigonometric arc sine of x (result in radians) asin( 0.0 ) = 0.0 atan( x ) Trigonometric arc tangent of x (result in radians) atan( 0.0 ) = 0.0 ceil( x ) Rounds x to the smallest integer not less than x ceil( 9.2 ) = 10.0 ceil( -9.8 ) = -9.0 cos( x ) Trigonometric cosine of x (x in radians) cos( 0.0 ) = 1.0 exp( x ) Exponential function ex exp( 1.0 ) = 2.71828 exp( 2.0 ) = 7.38906 fabs( x ) Absolute value of x fabs( 5.1 ) = 5.1 fabs( -5.1 ) = 5.1 floor( x ) Rounds x to the largest integer not greater than x floor( 9.2 ) = 9.0 floor( -9.8 ) = -10.0 fmod( x, y ) Remainder of x/y as a floating point number fmod( 9.8, 4.0 ) = 1.8 hypot( x, y ) hypotenuse of a triangle with sides of length x and y: sqrt( x2 + y2 ) hypot( 3.0, 4.0 ) = 5.0 log( x ) Natural logarithm of x (base e) log( 2.718282 ) = 1.0 log( 7.389056 ) = 2.0 log10( x ) Logarithm of x (base 10) log10( 10.0 ) = 1.0 log10( 100.0 ) = 2.0 pow( x, y ) x raised to power y (xy) pow( 2.0, 7.0 ) = 128.0 pow( 9.0, .5 ) = 3.0 sin( x ) trigonometric sine of x (x in radians) sin( 0.0 ) = 0.0 sqrt( x ) square root of x sqrt( 900.0 ) = 30.0 sqrt( 9.0 ) = 3.0 tan( x ) trigonometric tangent of x (x in radians) tan( 0.0 ) = 0.0 定义函数: def square( y ): ----------------------定义函数 square(y)为 y*y return y * y for x in range( 1, 11 ): ---------输出 1 到 10 的平方 print square( x ), print def maximumValue( x, y, z ): -----------------定义求最大值的函数 maximum = x if y > maximum: maximum = y if z > maximum: maximum = z return maximum a = int( raw_input( "Enter first integer: " ) ) b = int( raw_input( "Enter second integer: " ) ) c = int( raw_input( "Enter third integer: " ) ) # function call print "Maximum integer is:", maximumValue( a, b, c ) 应用于 integer print # print new line d = float( raw_input( "Enter first float: " ) ) e = float( raw_input( "Enter second float: " ) ) f = float( raw_input( "Enter third float: " ) ) print "Maximum float is: ", maximumValue( d, e, f ) 应用于 float print g = raw_input( "Enter first string: " ) h = raw_input( "Enter second string: " ) i = raw_input( "Enter third string: " ) print "Maximum string is: ", maximumValue( g, h, i ) 应用于字符串 string 2.2 random: import random for i in range( 1, 21 ): # simulates 20 die rolls print "%10d" % ( random.randrange( 1, 7 ) ), if i % 5 == 0: # print newline every 5 rolls print 2.3 dir()存储命名空间 最开始运行 dir()时: 得到 ['__builtins__', '__doc__', '__name__', '__package__'] print __builtins__ 得到:<module '__builtin__' (built-in)> print __doc__ 得到:None print __name__ 得到:__main__ print __package__ 得到:None 1 到 6 随机选取一个数 定义 x=3 dir() 得到:['__builtins__', '__doc__', '__name__', '__package__', 'x'] import math,random dir() 得到:['__builtins__', '__doc__', '__name__', 'math', 'random'] dir(math) 得到:['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh','e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hy-pot', 'ldexp', 'log', 'log10','modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] >>> from math import sqrt 也可以通过 from…import…导入单个方法 >>> dir() ['__builtins__', '__doc__', '__name__', 'sqrt'] >>> sqrt( 9.0 ) 3.0 >>> from math import * 导入 math 中所有函数 import random as randomModule 取别名 from math import sqrt as squareRoot 取别名 2.4 全局变量与局部变量: x = 1 # global variable 全局变量 # alters the local variable x, shadows the global variable def a(): x = 25 局部变量 print "\nlocal x in a is", x, "after entering a" x += 1 print "local x in a is", x, "before exiting a" # alters the global variable x def b(): global x 全局变量申明 print "\nglobal x is", x, "on entering b" x *= 10 print "global x is", x, "on exiting b" print "global x is", x x=7 print "global x is", x a() b() a() b() print "\nglobal x is", x 得到: global x is 1 global x is 7 local x in a is 25 after entering a local x in a is 26 before exiting a global x is 7 on entering b global x is 70 on exiting b local x in a is 25 after entering a local x in a is 26 before exiting a global x is 70 on entering b global x is 700 on exiting b global x is 700 2.5 递归调用: 阶乘的运算: def factorial( number ): if number <= 1: # base case return 1 else: return number * factorial( number - 1 ) # recursive call 递归调用 for i in range( 11 ): print "%2d! = %d" % ( i, factorial( i ) ) 得到:0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800 def fibonacci( n ): if n < 0: print "Cannot find the fibonacci of a negative number." if n == 0 or n == 1: # base case return n else: # two recursive calls return fibonacci( n - 1 ) + fibonacci( n - 2 ) ------------f(x)=f(x-1)+f(x-2) number = int( raw_input( "Enter an integer: " ) ) result = fibonacci( number ) print "Fibonacci(%d) = %d" % ( number, result ) def boxVolume( length = 1, width = 1, height = 1 ): -------默认 length = 1, width = 1, height = 1 return length * width * height print "The default box volume is:", boxVolume() print "\nThe volume of a box with length 10," print "width 1 and height 1 is:", boxVolume( 10 ) length=10 print "\nThe volume of a box with length 10," print "width 5 and height 1 is:", boxVolume( 10, 5 ) length=10 width=5 print "\nThe volume of a box with length 10," print "width 5 and height 2 is:", boxVolume( 10, 5, 2 ) length=10 width=5 height=2 第三章 Lists, Tuples and Dictionaries 3.1 Lists, Tuples aList = [ 1, 2, 3 ]等同于 aTuple = 1, 2, 3 等同于 aTuple = ( 1, 2, 3 ) len( aList )得到 aList 的长度 aString = "abc" 字符串 aList = [ 1, 2, 3 ] 同类数组,即数组成员均为同类型 aTuple = "a", "A", 1 可以存储非同类的数组 --------------数组中第三位即顺数第三位,若为-4 那么为倒数第四位 sequence[ i:j + 1 ] 从第 i 位到第 j+1 位 sequence[ 0 : len( sequence ) ] sequence[ : len( sequence ) ] sequence[ 0 : ] sliceString = "abcdefghij" sliceTuple = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ) sliceList = [ "I", "II", "III", "IV", "V","VI", "VII", "VIII", "IX", "X" ] print "sliceString: ", sliceString 数组打印不需要% print "sliceTuple: ", sliceTuple print "sliceList: ", sliceList print "\nsliceString[", start, ":", end, "] = ", sliceString[3:6 ] 打印第 3 位到第 6 位 playList = [] # list of favorite plays print "Enter your 5 favorite Shakespearean plays.\n" for i in range( 5 ): playName = raw_input( "Play %d: " % ( i + 1 ) ) 输入 5 次名字 playList.append( playName ) 加入至数组中,命名为 playName print "\nSubscript Value" for i in range( len( playList ) ): print "%9d %-25s" % ( i + 1, playList[ i ] ) %-25s 从左至右 25 位 responses = [ 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 ] print "Rating Frequency" for i in range( 1, 11 ): print "%6d %13d" % ( i, responses.count( i ) ) --- responses.count( i ) 1-10 在数组 responses 中出现的次数 Lists, Tuples 的函数 append( item ) Inserts item at the end of the list.将新项加入至数组的末尾 count( element ) Returns the number of occurrences of element in the list.返回元素 在数组中出现的次数 extend( newList ) Inserts the elements of newList at the end of the list.将新数组追加 在数组后 index( element ) Returns the index of the first occurrence of element in the list. If element is not in the list, a ValueError exception occurs. [Note: We discuss exceptions in Chapter 12, Exception Handling.] 返回元素在数组中的位置 insert( index, item ) Inserts item at position index 指定插入新项的位置 pop( [index] ) Parameter index is optional. If this method is called without arguments, it removes and returns the last element in the list. If parameter index is specified, this method removes and returns the element at position index.如果指定的位置存在则移除此位置的 元素,否则移除最后一项 remove( element ) Removes the first occurrence of element from the list. If element is not in the list, a ValueError exception occurs.移除元素 reverse() Reverses the contents of the list in place (rather than creating areversed copy).反序 sort( [compare-function] ) 排序,默认为从小到大 Sorts the content of the list in place. The optional parameter compare-function is a function that specifies the compare criteria. The compare-function takes any two elements of the list (x and y) and returns -1 if x should appear before y, 0 if the orders of x and y do not matter and 1 if x should appear after y.比 较方法选取任意 2 个元素 xy 为:若 x 出现在 y 之前则为-1,之 后则为 1,其他为 0 [Note: We discuss sorting in Section 5.9.] aList.sort()可以使数组从小到大排好序并存储 print "Found at index:", aList.index( searchKey ) 查找 3.2 Dictionary emptyDictionary = {} 定义一个空字典 print "The value of emptyDictionary is:", emptyDictionary # create and print a dictionary with initial values grades = { "John": 87, "Steve": 76, "Laura": 92, "Edwin": 89 } 成绩字典 print "\nAll grades:", grades # access and modify an existing dictionary print "\nSteve's current grade:", grades[ "Steve" ] 输出 Steve 的成绩 76 grades[ "Steve" ] = 90 更改 Steve 的成绩为 90 print "Steve's new grade:", grades[ "Steve" ] monthsDictionary = { 1 : "January", 2 : "February", 3 : "March", 4 : "April", 5 : "May", 6 : "June", 7 : "July",8 : "August", 9 : "September", 10 : "October",11 : "November", 12 : "December" } print "The dictionary items are:" print monthsDictionary.items() 1 : "January"为 item print "\nThe dictionary keys are:" print monthsDictionary.keys() 1 : "January"中 1 为 key print "\nThe dictionary values are:" print monthsDictionary.values() 1 : "January"中 January 为 value print "\nUsing a for loop to get dictionary items:" Dictionary 的函数 clear() Deletes all items from the dictionary.删除所有 copy() Creates and returns a shallow copy of the dictionary (the elements in the new dictionary are references to the elements in the original dictionary).复制 get( key [, returnValue] ) Returns the value associated with key. If key is not in the dictionary and if returnValue is specified, returns the specified value. If returnValue is not specified, returns None.得到指定 key 的值 Value has_key( key ) Returns 1 if key is in the dictionary; returns 0 if key is not in the dictionary.判断 key 是否存在于 dictionary,存在为 1,不存在 为0 items() Returns a list of tuples that are key-value pairs. keys() Returns a list of keys in the dictionary. popitem() Removes and returns an arbitrary key-value pair as a tuple of two elements. If dictionary is empty, a Key-Error exception occurs. [Note: We discuss exceptions in Chapter 12, Exception Handling.] This method is use-ful for accessing an element (i.e., print the key-value pair) before removing it from the dictionary. setdefault( key [, dummyValue] ) Behaves similarly to method get. If key is not in the dictionary and dummyValue is specified, inserts the key and the specified value into dictionary. If dummyValue is not specified, value is None. update( newDictionary ) Adds all key-value pairs from newDictionary to the current dictionary and overrides the values for keys that already exist. values() Returns a list of values in the dictionary iterkeys() Returns an iterator of dictionary keys. [Note: We discuss iterators in Appendix O, Additional Python 2.2 Features.] iteritems() Returns an iterator of key-value pairs. [Note: We discuss iterators in Appendix O, Additional Python 2.2 Features.] itervalues() Returns an iterator of dictionary values. [Note: We discuss iterators in Appendix O, Additional Python 2.2 Features.] >>> dictionary = { "listKey" : [ 1, 2, 3 ] } >>> shallowCopy = dictionary.copy() # make a shallow copy 浅复制,没有涉及其他的 python 的类 >>> dictionary[ "listKey" ].append( 4 ) 在 listKey 后追加元素 4 >>> print dictionary {'listKey': [1, 2, 3, 4]} >>> print shallowCopy {'listKey': [1, 2, 3, 4]} >>> from copy import deepcopy 从 copy 模块中导出 deepcopy 函数 >>> deepCopy = deepcopy( dictionary ) # make a deep copy 深复制,独立存在的,跟元数据 无关 >>> dictionary[ "listKey" ].append( 5 ) 在 listKey 后追加元素 5 >>> print dictionary {'listKey': [1, 2, 3, 4, 5]} >>> print shallowCopy 与当前相同 {'listKey': [1, 2, 3, 4, 5]} >>> print deepCopy 保持复制状态不变 {'listKey': [1, 2, 3, 4]} def modifyList( aList ): for i in range( len( aList ) ): aList[ i ] *= 2 数组中均乘以 2 def modifyElement( element ): element *= 2 元素乘以 2 aList = [ 1, 2, 3, 4, 5 ] print "Effects of passing entire list:" print "The values of the original list are:" for item in aList: print item, modifyList( aList ) --------数组中均乘以 2 ,保存在数组中 ,2 4 6 8 10 print "\n\nThe values of the modified list are:" for item in aList: print item, print "\n\nEffects of passing list element:" print "aList[ 3 ] before modifyElement:", aList[ 3 ] modifyElement( aList[ 3 ] ) ----元素乘以 2,但是为保存在数组中,所以再次输出数组 中元素时仍为 8 print "aList[ 3 ] after modifyElement:", aList[ 3 ] 3.3 二维数组 table2 = ( ( 1, 2 ), ( 3, ), ( 4, 5, 6 ) ) for row in table2: for item in row: print item, print 得到: 12 3 456 计算成绩最大值,最小值及平均成绩: def printGrades( grades ): ----------------输出成绩函数 students = len( grades ) # number of students exams = len( grades[ 0 ] ) # number of exams # print table headers print "The list is:" print " ", for i in range( exams ): print "[%d]" % i, 输出标号 print # print scores, by row for i in range( students ): print "grades[%d] " % i, for j in range( exams ): print grades[ i ][ j ], "", 输出成绩 print def minimum( grades ): -----------------成绩最高分 lowScore = 100 初始值设为 100 for studentExams in grades: # loop over students for score in studentExams: # loop over scores if score < lowScore: lowScore = score 将小的赋值给 lowScore return lowScore def maximum( grades ): -----------成绩最低分 highScore = 0 初始值为 0 for studentExams in grades: # loop over students for score in studentExams: # loop over scores if score > highScore: highScore = score 将大的赋值给 highScore return highScore def average( setOfGrades ): ----------平均成绩 total = 0.0 for grade in setOfGrades: # loop over student’s scores total += grade --------求总分 return total / len( setOfGrades ) -----返回平均成绩 # main program grades = [ [ 77, 68, 86, 73 ], [ 96, 87, 89, 81 ], [ 70, 90, 86, 81 ] ] printGrades( grades ) print "\n\nLowest grade:", minimum( grades ) print "Highest grade:", maximum( grades ) print "\n" # print average for each student for i in range( len( grades ) ): print "Average for student", i, "is", average( grades[ i ] ) 得到: The list is: [0] [1] [2] [3] grades[0] 77 68 86 73 grades[1] 96 87 89 81 grades[2] 70 90 86 81 Lowest grade: 68 Highest grade: 96 Average for student 0 is 76.0 Average for student 1 is 88.25 Average for student 2 is 81.75 第四章 Common Gateway Interface (CGI) 公共网关接口简介 4.1 服务模式 客户端--------Internet-----------------Web Server——CGI——Python applicattion 1. 客户端向 Web Server 请求服务 2. Web Server 接收到客户端请求后,到资源系统中寻找 3. Web Server 检测到 CGI 是工作的,开启一个输出口给客户端 4. 通过 CGI 将应用脚本交回给 Web Server 5. Web Server 回应客户端,并发送脚本结果 Unix 或者 linux 下要给出一下申明: #!/usr/bin/python #!/usr/local/bin/python #!/usr/bin/env python 4.1.1 显示时间 #!c:\Python\python.exe --------------------申明 import time ---------------导出模块 time def printHeader( title ): -----------打印主题函数 print """Content-type: text/html <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>%s</title></head> <body>""" % title printHeader( "Current date and time" ) print time.ctime( time.time() ) --------------输出当前时间 time.time() 返回一个浮点 型显示秒数的数值;time.ctime()依据秒数来显示一个人们可读的时间表达方法,即下图所示 print "</body></html>" ---------网页结束 chmod 755 fig06_02.py http://localhost/cgi-bin/fig06_02.py 可以进入查看效果,如上图 4.1.2 文本格式化 #!c:\Python\python.exe # Fig. 6.5: fig06_05.py # Program displaying CGI environment variables. import os import cgi -------这个模块提供了一些 CGI 的相关功能,包括文本格式化,表格处理和 URL 解析,下面使用文本格式化 def printHeader( title ): ------------------定义函数 print """Content-type: text/html <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>%s</title></head> <body>""" % title rowNumber = 0 backgroundColor = "white" printHeader( "Environment Variables" ) print """<table style = "border: 0">""" # print table of cgi variables and values for item in os.environ.keys(): rowNumber += 1 if rowNumber % 2 == 0: # even row numbers are white backgroundColor = "white" else: # odd row numbers are grey backgroundColor = "lightgrey" print """<tr style = "background-color: %s"> <td>%s</td><td>%s</td></tr>""" % ( backgroundColor,cgi.escape( item ), cgi.escape( os.environ[ item ] ) ) print """</table></body></html>""" 4.1.3 查询 #!c:\Python\python.exe # Fig. 6.6: fig06_06.py # Example using QUERY_STRING. import os import cgi def printHeader( title ): --------------定义函数 print """Content-type: text/html <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>%s</title></head> <body>""" % title printHeader( "QUERY_STRING example" ) print "<h1>Name/Value Pairs</h1>" query = os.environ[ "QUERY_STRING" ] ---------- os.environ 成员持有的所有数据环 境变量,这就像一个数据字典成员的行为,因此,我们可以通过的关键字的方法,通过[]操 作符获得其值 if len( query ) == 0: print """<p><br /> Please add some name-value pairs to the URL above. Or try <a href = "fig06_06.py?name=Veronica&amp;age=23">this</a>. </p>""" else: print """<p style = "font-style: italic"> The query string is '%s'.</p>""" % cgi.escape( query ) -------cgi.escape 接受一个字符 串,并返回正确的 XHTML 格式的字符串 pairs = cgi.parse_qs( query ) for key, value in pairs.items(): print "<p>You set '%s' to value %s</p>"" % \ ( key, value ) print "</body></html>" 标签及其属性 <input> button A standard push button. checkbox Displays a checkbox that can be checked (true) or unchecked (false). file Displays a text field and button so the user can specify a file to upload to a Web server. The button displays a file dialog that allows the user to select a file. hidden Hides data information from clients so that hidden form data can be used only by the form handler on the server. password Like text, but each character typed appears as an asterisk (*) to hide the input (for security). image The same as submit, but displays an image rather than a button. radio Radio buttons are similar to checkboxes, except that only one radio button in a group of radio buttons can be selected at a time. reset A button that resets form fields to their default values. submit A push button that submits form data according to the form’s action. text Provides single-line text field for text input. This attribute is the default input type. <select> Drop-down menu or selection box. When used with the <option> tag, <select> specifies items to select. <textarea> Multiline area in which text can be input or displayed. 4.1.4 输入框及按钮 #!c:\Python\python.exe import cgi def printHeader( title ): print """Content-type: text/html <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>%s</title></head> <body>""" % title printHeader( "Using 'get' with forms" ) print """<p>Enter one of your favorite words here:<br /></p> <form method = "get" action = "fig06_08.py"> <p> <input type = "text" name = "word" /> --------text 输入框 <input type = "submit" value = "Submit word" /> -------提交按钮 </p> </form>""" pairs = cgi.parse() if pairs.has_key( "word" ): --------------------关键字解析 print """<p>Your word is: <span style = "font-weight: bold">%s</span></p>""" \ % cgi.escape( pairs[ "word" ][ 0 ] ) print "</body></html>" 加上以下代码,效果同上: form = cgi.FieldStorage() ------------类似于解析函数返回数据字典 if form.has_key( "word" ): print """<p>Your word is: <span style = "font-weight: bold">%s</span></p>""" \ % cgi.escape( form[ "word" ].value ) print "</body></html>" 4.1.5 登陆校验 <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>Enter here</title></head> <body> <h1>Welcome to Bug2Bug Travel</h1> <form method = "post" action = "/cgi-bin/fig06_12.py"> <p>Please enter your name:<br /> <input type = "text" name = "name" /><br /> Members, please enter the password:<br /> <input type = "password" name = "password" /><br /> </p> <p style = "font-size: em - 1; font-style: italic" > Note that password is not encrypted.<br /><br /> <input type = "submit" /> </p> </form> </body> </html> 第五章 面向对象编程 定义一个私有类: # Fig. 7.11: Private.py class PrivateClass: """Class that contains public and private data""" def __init__( self ): """Private class, contains public and private data members""" self.publicData = "public" # public data member 公有数据 self.__privateData = "private" # private data member 私有数据 >>> from Private import PrivateClass ------------------从文件中导入 PrivateClass >>> private = PrivateClass() >>> print private.publicData -------------输出公有数据 public >>> print private.__privateData Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: PrivateClass instance has no attribute '__privateData' >>> >>> print private._PrivateClass__privateData ----------输出私有数据的正确方法 private >>> private._PrivateClass__privateData = "modified" ---允许赋值 >>> print private._PrivateClass__privateData modified 定义一个时间类,其中能输出标准时间: # Fig: 7.13: Time3.py # Class Time with default constructor. class Time: """Class Time with default constructor""" def __init__( self, hour = 0, minute = 0, second = 0 ): ----------初始化 """Time constructor initializes each data member to zero""" self.setTime( hour, minute, second ) --------调用以下函数 def setTime( self, hour, minute, second ): """Set values of hour, minute, and second""" self.setHour( hour ) --------调用以下小时设置函数 self.setMinute( minute ) -------调用以下分设置函数 self.setSecond( second ) -------调用以下秒设置函数 def setHour( self, hour ): """Set hour value""" if 0 <= hour < 24: self.__hour = hour else: raise ValueError, "Invalid hour value: %d" % hour def setMinute( self, minute ): """Set minute value""" if 0 <= minute < 60: self.__minute = minute else: raise ValueError, "Invalid minute value: %d" % minute def setSecond( self, second ): """Set second value""" if 0 <= second < 60: self.__second = second else: raise ValueError, "Invalid second value: %d" % second def getHour( self ): """Get hour value""" return self.__hour def getMinute( self ): """Get minute value""" return self.__minute def getSecond( self ): """Get second value""" return self.__second def printMilitary( self ): ----------------输出时间 """Prints Time object in military format""" print "%.2d:%.2d:%.2d" % \ ( self.__hour, self.__minute, self.__second ), def printStandard( self ): --------------------转换输出标准时间 """Prints Time object in standard format""" standardTime = "" if self.__hour == 0 or self.__hour == 12: standardTime += "12:" else: standardTime += "%d:" % ( self.__hour % 12 ) standardTime += "%.2d:%.2d" % ( self.__minute, self.__second ) if self.__hour < 12: standardTime += " AM" else: standardTime += " PM" print standardTime, ------------------------------输出标准时间 调用以上时间类来显示时间: from Time3 import Time def printTimeValues( timeToPrint ): timeToPrint.printMilitary() print timeToPrint.printStandard() print time1 = Time() # all default time2 = Time( 2 ) # minute, second default time3 = Time( 21, 34 ) # second default time4 = Time( 12, 25, 42 ) # all specified print "Constructed with:" print "\nall arguments defaulted:" printTimeValues( time1 ) print "\nhour specified; minute and second defaulted:" printTimeValues( time2 ) print "\nhour and minute specified; second defaulted:" printTimeValues( time3 ) print "\nhour, minute and second specified:" printTimeValues( time4 ) 得到结果: Constructed with: all arguments defaulted: 00:00:00 12:00:00 AM hour specified; minute and second defaulted: 02:00:00 2:00:00 AM hour and minute specified; second defaulted: 21:34:00 9:34:00 PM hour, minute and second specified: 12:25:42 12:25:42 PM 定义员工类: class Employee: """Represents an employee""" count = 0 # class attribute def __init__( self, first, last ): """Initializes firstName, lastName and increments count""" self.firstName = first self.lastName = last Employee.count += 1 # increment class attribute print "Employee constructor for %s, %s" \ % ( self.lastName, self.firstName ) def __del__( self ): """Decrements count and prints message""" Employee.count -= 1 # decrement class attribute print "Employee destructor for %s, %s" \ % ( self.lastName, self.firstName ) 调用员工类: from EmployeeWithClassAttribute import Employee print "Number of employees before instantiation is", \ Employee.count # create two Employee objects employee1 = Employee( "Susan", "Baker" ) employee2 = Employee( "Robert", "Jones" ) employee3 = employee1 print "Number of employees after instantiation is", \ employee1.count # explicitly delete employee objects by removing references del employee1 del employee2 del employee3 print "Number of employees after deletion is", \ Employee.count 结果: Number of employees before instantiation is 0 Employee constructor for Baker, Susan Employee constructor for Jones, Robert Number of employees after instantiation is 2 Employee destructor for Jones, Robert Employee destructor for Baker, Susan Number of employees after deletion is 0 定义日期类: class Date: """Class that represents dates""" # class attribute lists number of days in each month daysPerMonth = [ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] def __init__( self, month, day, year ): """Constructor for class Date""" if 0 < month <= 12: # validate month self.month = month else: raise ValueError, "Invalid value for month: %d" % month if year >= 0: # validate year self.year = year else: raise ValueError, "Invalid value for year: %y" % year self.day = self.checkDay( day ) # validate day print "Date constructor:", self.display() def __del__( self ): """Prints message when called""" print "Date object about to be destroyed:", self.display() def display( self ): """Prints Date information""" print "%d/%d/%d" % ( self.month, self.day, self.year ) def checkDay( self, testDay ): """Validates day of the month""" # validate day, test for leap year if 0 < testDay <= Date.daysPerMonth[ self.month ]: return testDay elif self.month == 2 and testDay == 29 and \ ( self.year % 400 == 0 or self.year % 100 != 0 and self.year % 4 == 0 ): return testDay else: raise ValueError, "Invalid day: %d for month: %d" % \ ( testDay, self.month ) 调用日期类来定义员工类: from Date import Date class Employee: """Employee class with Date attributes""" def __init__( self, firstName, lastName, birthMonth, birthDay, birthYear, hireMonth, hireDay, hireYear ): """Constructor for class Employee""" self.birthDate = Date( birthMonth, birthDay, birthYear ) self.hireDate = Date( hireMonth, hireDay, hireYear ) self.lastName = lastName self.firstName = firstName print "Employee constructor: %s, %s" \ % ( self.lastName, self.firstName ) def __del__( self ): """Called before Employee destruction""" print "Employee object about to be destroyed: %s, %s" \ % ( self.lastName, self.firstName ) def display( self ): """Prints employee information""" print "%s, %s" % ( self.lastName, self.firstName ) print "Hired:", self.hireDate.display() print "Birth date:", self.birthDate.display() 调用日期类员工类: from Date import Date from EmployeeComposition import Employee employee = Employee( "Bob", "Jones", 7, 24, 1949, 3, 12, 1988 ) print employee.display() print 得到结果: Date constructor: 7/24/1949 Date constructor: 3/12/1988 Employee constructor: Jones, Bob Jones, Bob Hired: 3/12/1988 Birth date: 7/24/1949 Employee object about to be destroyed: Jones, Bob Date object about to be destroyed: 3/12/1988 Date object about to be destroyed: 7/24/1949 第六章 用户自定义类 6.1 自定义的字符串表示方法: __str__ 定义电话号码类: # Fig. 8.1: PhoneNumber.py # Representation of phone number in USA format: (xxx) xxx-xxxx. class PhoneNumber: --------------电话号码类结构定义 """Simple class to represent phone number in USA format""" def __init__( self, number ): --------------初始化 """Accepts string in form (xxx) xxx-xxxx""" self.areaCode = number[ 1:4 ] # 3-digit area code -------3 位区号 self.exchange = number[ 6:9 ] # 3-digit exchange -------3 位 self.line = number[ 10:14 ] # 4-digit line -------4 位 def __str__( self ): """Informal string representation""" return "(%s) %s-%s" % ( self.areaCode, self.exchange, self.line ) -----输出格式 def test(): # obtain phone number from user newNumber = raw_input( "Enter phone number in the form (123) 456-7890:\n" ) phone = PhoneNumber( newNumber ) --------创建电话号码类 print "The phone number is:", print phone -----------调用 phone.__str__(),输出电话号码类 if __name__ == "__main__": ------python 默认将__main__存储于命名空间中__name__ test() -------调用 test() 得到: Enter phone number in the form (123) 456-7890: (800) 555-1234 The phone number is: (800) 555-1234 6.2 自定义属性访问 __delattr__() 删除一个属性中的值就执行 __getattr__() 客户端访问时一个不位于对象__dict__的属性名称才执行 __setattr__() 给一个属性赋值就执行 定义时间类结构: class Time: """Class Time with customized attribute access""" def __init__( self, hour = 0, minute = 0, second = 0 ): -----初始化为 0:0:0 """Time constructor initializes each data member to zero""" # each statement invokes __setattr__ self.hour = hour self.minute = minute self.second = second def __setattr__( self, name, value ): -------------__setattr__()为赋值就执行 """Assigns a value to an attribute""" if name == "hour": if 0 <= value < 24: self.__dict__[ "_hour" ] = value ----------给小时赋值 else: raise ValueError, "Invalid hour value: %d" % value elif name == "minute" or name == "second": if 0 <= value < 60: self.__dict__[ "_" + name ] = value -----给分或者秒赋值 else: raise ValueError, "Invalid %s value: %d" % \ ( name, value ) else: self.__dict__[ name ] = value def __getattr__( self, name ): ----------获取 """Performs lookup for unrecognized attribute name""" if name == "hour": return self._hour elif name == "minute": return self._minute elif name == "second": return self._second else: raise AttributeError, name def __str__( self ): ----------输出 """Returns Time object string in military format""" # attribute access does not call __getattr__ return "%.2d:%.2d:%.2d" % ( self._hour, self._minute, self._second ) >>> from TimeAccess import Time >>> time1 = Time( 4, 27, 19 ) >>> print time1 04:27:19 >>> print time1.hour, time1.minute, time1.second 4 27 19 >>> time1.hour = 16 >>> print time1 16:27:19 >>> time1.second = 90 Traceback (most recent call last): File "<stdin>", line 1, in ? File "TimeAccess.py", line 30, in __setattr__ raise ValueError, "Invalid %s value: %d" % \ ValueError: Invalid second value: 90 6.3 重载二元运算符 一元运算符 特殊方法 - __neg__ + __pos__ ~ __invert__ 二元运 算符 特殊方法 二元运 算符 特殊方法 / __div__, __rdiv__, __truediv__ (for Python 2.2), __rtruediv__ (for Python 2.2) + __add__, __radd__ // __floordiv__, __rfloordiv__ (for Python version 2.2) * __mul__, __rmul__ % __mod__, __rmod__ - __sub__重载二进制减法运 算符。此方法使用重载+和 - 运算符,创建并返回 __sub__第一个参数减去 __sub__第二个参数结果。, __rsub__ ** __pow__, __rpow__ | __or__, __ror__ << __lshift__, __rlshift__ >> __rshift__, __rrshift__ & __and__, __rand__ ^ __xor__, __rxor__ += __iadd__ -= __isub__ *= __imul__ /= __idiv__, __itruediv__ (for Python version 2.2) //= __ifloordiv__ (for Python version 2.2) %= __imod__ **= __ipow__ <<= __ilshift__ >>= __irshift__ &= __iand__ ^= __ixor__ |= __ior__ == __eq__ !+, <> __ne__ > __gt__ < __lt__ >= __ge__ <= __le__ 6.4 类型之间的转换 常见的内置函数及其相应的特殊方法 内置函数 描述 特殊方法 abs( x ) Returns the absolute value of x. 返回 x 的绝对值 __abs__ divmod( x, y ) Returns a tuple that contains the integer and remainder components of x % y. 返回一个元组包含整数,其余 组成部分为 x % y. __divmod__ len( x ) Returns the length of x (x should be a sequence).序列 x 的长度 __len__ pow( x, y[, z] ) Returns the result of xy. With three arguments, returns (xy) % z.只有 xy 则返回 xy 的乘积,有 z 则返回 xy 的乘积除以 z 的结果 __pow__ repr( x ) Returns a formal string representation of x (i.e., a string from which object x can be replicated).返回 x 的 字符串表现形式 __repr__ 强制的方法 描述 __coerce__ Converts two values to the same type.将 2 中值转换为相同类型 __complex__ Converts object to complex number type.转换成复数 __float__ Converts object to floating-point number type.转换成浮点型 __hex__ Converts object to hexidecimal string type.转换成十六进制 __int__ Converts object to integer number type.转换成数字整型 __long__ Converts object to long integer number type.转换成长整型 __oct__ Converts object to octal string type.转换成八进制字符串 __str__ Converts object to string type. Also used to obtain informal string representation of object (i.e., a string that simply describes object).转换成字符串 例: def gcd( x, y ): """Computes greatest common divisor of two values""" while y: z=x x=y y=z%y return x class Rational: """Representation of rational number""" def __init__( self, top = 1, bottom = 1 ): """Initializes Rational instance""" # do not allow 0 denominator if bottom == 0: raise ZeroDivisionError, "Cannot have 0 denominator" # assign attribute values self.numerator = abs( top ) self.denominator = abs( bottom ) self.sign = ( top * bottom ) / ( self.numerator * self.denominator ) self.simplify() # Rational represented in reduced form # class interface method def simplify( self ): """Simplifies a Rational number""" common = gcd( self.numerator, self.denominator ) self.numerator /= common self.denominator /= common # overloaded unary operator def __neg__( self ): """Overloaded negation operator""" return Rational( -self.sign * self.numerator, self.denominator ) # overloaded binary arithmetic operators def __add__( self, other ): """Overloaded addition operator""" return Rational( self.sign * self.numerator * other.denominator + other.sign * other.numerator * self.denominator, self.denominator * other.denominator ) def __sub__( self, other ): """Overloaded subtraction operator""" return self + ( -other ) def __mul__( self, other ): """Overloaded multiplication operator""" return Rational( self.numerator * other.numerator, self.sign * self.denominator * other.sign * other.denominator ) def __div__( self, other ): """Overloaded / division operator.""" return Rational( self.numerator * other.denominator, self.sign * self.denominator * other.sign * other.numerator ) def __truediv__( self, other ): """Overloaded / division operator. (For use with Python versions (>= 2.2) that contain the // operator)""" return self.__div__( other ) # overloaded binary comparison operators def __eq__( self, other ): """Overloaded equality operator""" return ( self - other ).numerator == 0 def __lt__( self, other ): """Overloaded less-than operator""" return ( self - other ).sign < 0 def __gt__( self, other ): """Overloaded greater-than operator""" return ( self - other ).sign > 0 def __le__( self, other ): """Overloaded less-than or equal-to operator""" return ( self < other ) or ( self == other ) def __ge__( self, other ): """Overloaded greater-than or equal-to operator""" return ( self > other ) or ( self == other ) def __ne__( self, other ): """Overloaded inequality operator""" return not ( self == other ) # overloaded built-in functions def __abs__( self ): """Overloaded built-in function abs""" return Rational( self.numerator, self.denominator ) def __str__( self ): """String representation""" # determine sign display if self.sign == -1: signString = "-" else: signString = "" if self.numerator == 0: return "0" elif self.denominator == 1: return "%s%d" % ( signString, self.numerator ) else: return "%s%d/%d" % \ ( signString, self.numerator, self.denominator ) # overloaded coercion capability def __int__( self ): """Overloaded integer representation""" return self.sign * divmod( self.numerator, self.denominator )[ 0 ] def __float__( self ): """Overloaded floating-point representation""" return self.sign * float( self.numerator ) / self.denominator def __coerce__( self, other ): """Overloaded coercion. Can only coerce int to Rational""" if type( other ) == type( 1 ): return ( self, Rational( other ) ) else: return None 调用: from RationalNumber import Rational # create objects of class Rational rational1 = Rational() # 1/1 rational2 = Rational( 10, 30 ) # 10/30 (reduces to 1/3) rational3 = Rational( -7, 14 ) # -7/14 (reduces to -1/2) # print objects of class Rational print "rational1:", rational1 print "rational2:", rational2 print "rational3:", rational3 print # test mathematical operators print rational1, "/", rational2, "=", rational1 / rational2 print rational3, "-", rational2, "=", rational3 - rational2 print rational2, "*", rational3, "-", rational1, "=", \ rational2 * rational3 - rational1 # overloading + implicitly overloads += rational1 += rational2 * rational3 print "\nrational1 after adding rational2 * rational3:", rational1 print # test comparison operators print rational1, "<=", rational2, ":", rational1 <= rational2 print rational1, ">", rational3, ":", rational1 > rational3 print # test built-in function abs print "The absolute value of", rational3, "is:", abs( rational3 ) print # test coercion print rational2, "as an integer is:", int( rational2 ) print rational2, "as a float is:", float( rational2 ) print rational2, "+ 1 =", rational2 + 1 得到: rational1: 1 rational2: 1/3 rational3: -1/2 1 / 1/3 = 3 -1/2 - 1/3 = -5/6 1/3 * -1/2 - 1 = -7/6 rational1 after adding rational2 * rational3: 5/6 5/6 <= 1/3 : 0 5/6 > -1/2 : 1 The absolute value of -1/2 is: 1/2 1/3 as an integer is: 0 1/3 as a float is: 0.333333333333 1/3 + 1 = 4/3 import re --imports the regular-expression module re, which provides regular-expression processing capabilities in Python. --Function re.compile takes as an argument a regular expression and returns --an SRE_Pattern object that represents a compiled regular expression. Compiled regular --expression objects provide all the functionality available in module re. For example, com--piled-expression object method search corresponds to function re.search --As the output demonstrates, both approaches return an SRE_Match object. This --object supports various methods for retrieving the results of regular-expression processing. --Method group (lines 26–28) returns the substring that matches the pattern. We discuss this --method further when we discuss grouping in Section 13.11. testString = "Hello world" formatString = "%-35s: %s" # string for formatting the output %-35s 从左至右 35 个字符 # create regular expression and compiled expression expression = "Hello" compiledExpression = re.compile( expression ) 编译正则表达式-》SRE_Pattern object # print expression and compiled expression print formatString % ( "The expression", expression ) 得到:The expression : Hello print formatString % ( "The compiled expression",compiledExpression ) ???? 得到:The compiled expression : <_sre.SRE_Pattern object at 0x2b2207701d20> 相当于通过了加密,主要应用于 python 编程后对程序加密使得其他人不能阅读 # search using re.search and compiled expression's search method print formatString % ( "Non-compiled search",re.search( expression, testString ) ) ???? 得到:Non-compiled search : <_sre.SRE_Match object at 0x2b220776e710> print formatString % ( "Compiled search",compiledExpression.search( testString ) ) ???? 得到:Compiled search : <_sre.SRE_Match object at 0x2b220776e710> # print results of searching print formatString % ( "search testString ).group() ) ???? 得到:search SRE_Match contains SRE_Match contains",re.search( expression, : Hello print formatString % ( "compiled contains",compiledExpression.search( testString ).group() ) 得到:compiled search SRE_Match contains : Hello string1 = "Now I am here." print string1.center( 50 ) 50 长度,字符处于中间 print string1.rjust( 50 ) 50 长度,字符处于右边 print string1.ljust( 50 ) 50 长度,字符处于左边 得到: Now I am here. Now I am here. search SRE_Match ???? Now I am here. string1 = "\t \n This is a test string. \t\t \n" print 'Original string: "%s"' % string1 print 'Using strip: "%s"' % string1.strip() 中字符串左右两边的\t\n 等删掉 print 'Using left strip: "%s"' % string1.lstrip() 字符串左边的\t\n 等删掉 print 'Using right strip: "%s"' % string1.rstrip() 字符串右边的\t\n 等删掉 得到: Original string: " This is a test string. " Using strip: "This is a test string." Using left strip: "This is a test string. " Using right strip: " This is a test string." string1.strip()为将 string1 string1.strip()为将 string1 中 string1.strip()为将 string1 中 string1 = "Test1, test2, test3, test4, Test5, test6" print '"test" occurs %d times in \n\t%s' %( string1.count( "test" ), string1 ) 获取字符串中 test 出现的次数 print '"test" occurs %d times after 18th character in \n\t%s' %( string1.count( "test", 18, len( string1 ) ), string1 ) 获取字符串前 18 个字符串中 test 出现的次数 print 换行 # finding a substring in a string string2 = "Odd or even" print '"%s" contains "or" starting at index %d' %( string2, string2.find( "or" ) ) 第几个位 置出现 or # find index of "even" try: ------------------------------try:...expect ValueError:... print '"even" index is', string2.index( "even" ) even 是第几个位置出 现的 except ValueError: print '"even" does not occur in "%s"' % string2 如果字符串中没有出 现 even,那么就打印出来 if string2.startswith( "Odd" ): string2.startswith( "Odd" )判断起始是否为 Odd print '"%s" starts with "Odd"' % string2 if string2.endswith( "even" ): string2.endswith( "even" )判断是否以 even 结束 print '"%s" ends with "even"\n' % string2 # searching from end of string print 'Index from end of "test" in "%s" is %d' % ( string1, string1.rfind( "test" ) ) 字符串 从右开始找 test 的位置 print # find rindex of "Test" try: print 'First occurrence of "Test" from end at index',string1.rindex( "Test" ) 从右开 始 test 出现的位置 except ValueError: print '"Test" does not occur in "%s"' % string1 为包含 test print # replacing a substring string3 = "One, one, one, one, one, one" print "Original:", string3 print 'Replaced "one" with "two":',string3.replace( "one", "two" ) ------string3.replace( "one", "two" )将字符串中所有 one 转换成 two print "Replaced 3 maximum:", string3.replace( "one", "two", 3 ) -----string3.replace( "one", "two", 3 )将字符串中前 3 个 one 转换成 two string1 = "A, B, C, D, E, F" print "String is:", string1 print "Split string by spaces:", string1.split() 隔 print "Split string by commas:", string1.split( "," ) print "Split string by commas, max 2:", string1.split( ",", 2 ) 只间隔 2 次 print # joining strings list1 = [ "A", "B", "C", "D", "E", "F" ] string2 = "___" print "List is:", list1 print 'Joining with "%s": %s' %( string2, string2.join ( list1 ) ) 之间,得到:Joining with "___": A___B___C___D___E___F print 'Joining with "-.-":', "-.-".join( list1 ) 之间,得到:Joining with "-.-": A-.-B-.-C-.-D-.-E-.-F import re ???? string1.split() 按空格间 string1.split( "," )按,间隔 string1.split( ",", 2 )按,间隔, 将 string2 加在 list1 各个字母 将"-.-"加在 list1 各个字母 # list of strings to search and expressions used to search testStrings = [ "Hello World", "Hello world!", "hello world" ] expressions = [ "hello", "Hello", "world!" ] # search every expression in every string for string in testStrings: --------for...in... for expression in expressions: if re.search( expression, string ): re.search( expression, string ) 判断 expression 是否存在于 string 中 print expression, "found in string", string else: print expression, "not found in string", string print import re testStrings = [ "Heo", "Helo", "Hellllo" ] expressions = [ "Hel?o", "Hel+o", "Hel*o" ] # match every expression with every string for expression in expressions: for string in testStrings: if re.match( expression, string ): 匹配 print expression, "matches", string else: print expression, "does not match", string print 得到:匹配字符含义 ? 最多一个字符 + 至少一个字符 * 任意字符 import re # specifying character classes with [ ] testStrings = [ "2x+5y","7y-3z" ] expressions = [ r"2x\+5y|7y-3z", r"[0-9][a-zA-Z0-9_].[0-9][yz]", r"\d\w-\d\w" ] # match every expression with every string for expression in expressions: for testString in testStrings: if re.match( expression, testString ): print expression, "matches", testString # specifying character classes with special sequences testString1 = "800-123-4567" testString2 = "617-123-4567" testString3 = "email: \t joe_doe@deitel.com" expression1 = r"^\d{3}-\d{3}-\d{4}$" expression2 = r"\w+:\s+\w+@\w+\.(com|org|net)" # matching with character classes if re.match( expression1, testString1 ): print expression1, "matches", testString1 if re.match( expression1, testString2 ): print expression1, "matches", testString2 if re.match( expression2, testString3 ): print expression2, "matches", testString3 得到: 2x\+5y|7y-3z matches 2x+5y 2x\+5y|7y-3z matches 7y-3z [0-9][a-zA-Z0-9_].[0-9][yz] matches 2x+5y [0-9][a-zA-Z0-9_].[0-9][yz] matches 7y-3z \d\w-\d\w matches 7y-3z ^\d{3}-\d{3}-\d{4}$ matches 800-123-4567 ^\d{3}-\d{3}-\d{4}$ matches 617-123-4567 \w+:\s+\w+@\w+\.(com|org|net) matches email: joe_doe@deitel.com import re testString1 = "This sentence ends in 5 stars *****" testString2 = "1,2,3,4,5,6,7" testString3 = "1+2x*3-y" formatString = "%-34s: %s" # string to format output print formatString % ( "Original string", testString1 ) # regular expression substitution testString1 = re.sub( r"\*", r"^", testString1 ) print formatString % ( "^ substituted for *", testString1 ) testString1 = re.sub( r"stars", "carets", testString1 ) print formatString % ( '"carets" substituted for "stars"',testString1 ) print formatString % ( 'Every word replaced by "word"',re.sub( r"\w+", "word", testString1 ) ) print formatString % ( 'Replace first 3 digits by "digit"',re.sub( r"\d", "digit", testString2, 3 ) ) # regular expression splitting print formatString % ( "Splitting " + testString2,re.split( r",", testString2 ) ) print formatString % ( "Splitting " + testString3,re.split( r"[+\-*/%]", testString3 ) ) 得到: Original string : This sentence ends in 5 stars ***** ^ substituted for * : This sentence ends in 5 stars ^^^^^ "carets" substituted for "stars" : This sentence ends in 5 carets ^^^^^ Every word replaced by "word" : word word word word word word ^^^^^ Replace first 3 digits by "digit" : digit,digit,digit,4,5,6,7 Splitting 1,2,3,4,5,6,7 : ['1', '2', '3', '4', '5', '6', '7'] Splitting 1+2x*3-y : ['1', '2x', '3', 'y'] import re formatString1 = "%-22s: %s" # string to format output # string that contains fields and expression to extract fields testString1 = "Albert Antstein, phone: 123-4567, e-mail: albert@bug2bug.com" expression1 = r"(\w+ \w+), phone: (\d{3}-\d{4}), e-mail: (\w+@\w+\.\w{3})" print formatString1 % ( "Extract all user data", re.match( expression1, testString1 ).groups() ) print formatString1 % ( "Extract user e-mail", re.match( expression1, testString1 ).group( 3 ) ) # greedy operations and grouping formatString2 = "%-38s: %s" # string to format output # strings and patterns to find base directory in a path pathString = "/books/2001/python" # file path string expression2 = "(/.+)/" # greedy operator expression print formatString1 % ( "Greedy error", re.match( expression2, pathString ).group( 1 ) ) expression3 = "(/.+?)/" # non-greedy operator expression print formatString1 % ( "No error, base only", re.match( expression3, pathString ).group( 1 ) ) 得到: Extract all user data : ('Albert Antstein', '123-4567', 'albert@bug2bug.com') Extract user e-mail : albert@bug2bug.com Greedy error : /books/2001 No error, base only : /books