Python 语法

  • python 一切都是对象,变量也是

基础语法

一、常用语法

1、HELLO WORLD

  1. * 创建文件
  2. touch test.py
  3. print "hello world";
  4. 1.指定路径执行
  5. /usr/bin/python test.py
  6. 2.文件首行写执行环境,像 shell #!/bin/bash
  7. #!/usr/bin/python
  8. ./test.py

2、数据类型

  1. 1、字符串
  2. 1) str='this is string';
  3. 2) 多行字符串
  4. str='''this is string
  5. this is pythod string
  6. this is string'''
  7. print str;
  8. 2、布尔类型
  9. bool=False;
  10. 3、整数
  11. int=20;
  12. 4、浮点数
  13. float=2.3;
  14. 5、数字
  15. 包括整数、浮点数
  16. 6、列表 list
  17. list=['physics', 'chemistry', 1997, 2000];
  18. 7、元组 tuple
  19. tup1 = ('physics', 'chemistry', 1997, 2000);
  20. 8、字典
  21. dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'};
  22. 9、日期
  23. import time, datetime;
  24. http://www.cnblogs.com/linjiqin/p/3608541.html
  25. time.sleep()

3、变量赋值

  1. 1. 统一赋值
  2. x , y , z = 1 , 2 , 3
  3. 2. 元祖赋值
  4. x = 1,2,3
  5. print x
  6. (1, 2, 3)
  7. 3. 链式赋值
  8. x = y = 1
  9. 4. 查看变量类型
  10. x.__class__
  11. 5. 定义全局变量
  12. global a;

4、逻辑判断

  1. 1.bool() 函数验证参数布尔值
  2. print bool(1)
  3. 2.if elif else
  4. name = raw_input("what's you name");
  5. if name.endswith("jason"):
  6. print "hello" + name;
  7. elif name.endswith("ray"):
  8. print "hello" + name
  9. else:
  10. print "who are youj"
  11. 3.表达式
  12. x == y
  13. x != y
  14. x is y x y 是同一个对象
  15. x is not y x y 不是同一个对象
  16. x in y x y 容器 (如,序列) 的成员
  17. x not in y x 不是 y 容器 (如,序列) 的成员
  18. 4. and or
  19. 1) if ("a" == "a") and ("aaa" == "aaa1"):
  20. false
  21. 2) if ("a" == "a") or ("aaa" == "aaa1"):
  22. true
  23. 4. None
  24. if xxx is None:
  25. pass
  26. 5. in
  27. if xxx in (aaaa,bbb,ccc)
  28. pass
  29. 6. 三元表达式
  30. status = True
  31. status and 'Y' or 'N'

5、循环

  1. * ps
  2. continue 跳过当前循环
  3. break 退出循环
  4. 1. while
  5. status = True;
  6. i = 0;
  7. while status == True :
  8. print i
  9. i += 1;
  10. if i > 100 :
  11. status = False
  12. 2. for
  13. 1) 普通循环
  14. codes = ['a','b','c','d','e','f','g','h','i','j']
  15. for now_code in codes:
  16. print now_code
  17. 2) 字典遍历
  18. map_data = {'a': 1 , 'b' : 2 , 'c' : 3}
  19. for key in map_data:
  20. print key , "-" , map_data[key]
  21. 3) 深度遍历
  22. for i,obj in [('host', '10.10.2.91'), ('user', 'hadoop')]:
  23. print i,obj
  24. host 10.10.2.91
  25. user hadoop
  26. 4) 循环次数,0 10
  27. import math
  28. for i in range(0,10):
  29. print i
  30. 在需要的时候生成 list
  31. for i in xrange(0,10):
  32. print i
  33. 5) 字典遍历
  34. person={'name':'lizhong','age':'26','city':'BeiJing','blog':'www.jb51.net'}
  35. for key,value in person.items():
  36. print 'key=',key,',value=',value
  37. key= blog value= www.jb51.net
  38. key= city value= BeiJing
  39. key= age value= 26
  40. key= name value= lizhong

6、自省

  1. 1. pass 当前行跳过,相当远行占位符
  2. 2. del 删除变量名,但不删除内存数据
  3. x = 1
  4. del x
  5. 3. exec() 执行字符语句
  6. 1) 一般执行
  7. exec "print 'hello world'"
  8. 2) 命名空间执行
  9. nameSpace = {} #定义一个字段
  10. exec "a = 1" in nameSpace; #把执行的数据放入字段中
  11. print nameSpace['a'] #即可全局获取
  12. 4. eval() 用于求值
  13. print eval("1 + 2")
  14. 5. help() 帮助
  15. help(str)
  16. 6. type() 查看数据类型
  17. type("Hello")
  18. 7. isinstance() 验证一个对象,是否是另外一个对象的类型
  19. isinstance('hellow',str)
  20. 8. dir() 查看对象所有的函数
  21. dir(str)

二、字符串

  1. 1. print "Let's go" + ",Jason"
  2. 2. repr() ``(不建议使用 ``) 是把结果字符串转换为合法的 Python 表达式
  3. 1) print repr("Hello,world!");
  4. 'Hello,world!'
  5. 2) print repr(10000L);
  6. 10000L
  7. 3) x = "test";
  8. print repr(x);
  9. 'test'
  10. 3. str() 把值转换成字符串
  11. 1) print str("Hello World");
  12. Hello World
  13. 2) print str(10000L);
  14. 10000
  15. 4. print r 原始字符输出
  16. 1) print r'C:\Program'
  17. C:\Program
  18. 5. 字符串连接
  19. 1) 关键字 %
  20. str = "%s %s"%('a','b');
  21. 字典替换
  22. str = '''%(a)s %(b)s %(c)s'''% {'a':'a1', 'b':'b1', 'c':'c1'}
  23. %c 转换成字符(ASCII 码值,或者长度为一的字符串)
  24. %r 优先用 repr()函数进行字符串转换
  25. %s 优先用 str()函数进行字符串转换
  26. %d / %i 转成有符号十进制数
  27. %ub 转成无符号十进制数
  28. %ob 转成无符号八进制数
  29. %xb/%Xb (Unsigned)转成无符号十六进制数(x/X 代表转换后的十六进制字符的大小写)
  30. %e/%E 转成科学计数法(e/E 控制输出 e/E)
  31. %f/%F 转成浮点数(小数部分自然截断)
  32. %g/%G %e 和%f/%E 和%F 的简写
  33. %% 输出%
  34. 2) join
  35. var_list = ['tom', 'david', 'john']
  36. #按照 , 号组合
  37. str = ','.join(var_list)
  38. 3) 元祖
  39. xx = 'Jim', 'Green'
  40. str = ','.join(xx)
  41. 4) 字符串连接
  42. str = "Let's go" + ",Jason"
  43. 6. split 分割字符串
  44. s = u'1*2*3*4'
  45. s.split('*')
  46. [u'1', u'2', u'3', u'4']
  47. 7. join 字符串
  48. s = u'alexzhou'
  49. u'*'.join(s)
  50. u'a*l*e*x*z*h*o*u'
  51. 8. replace 替换字符串
  52. s = u'111111'
  53. s.replace('1','2')
  54. u'222222'
  55. 9. 正则表达式
  56. *) 参数说明
  57. pattern: 匹配的正则表达式
  58. string: 要匹配的字符串
  59. flags: 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。
  60. re.I 使匹配对大小写不敏感
  61. re.L 做本地化识别(locale-aware)匹配
  62. re.M 多行匹配,影响 ^ $
  63. re.S 使 . 匹配包括换行在内的所有字符
  64. re.U 根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.
  65. re.X 该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。
  66. 1) re.match(pattern, string, flags=0), 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none
  67. import re
  68. pattern = r'(.*) are (.*?) .*'
  69. line = "Cats are smarter than dogs"
  70. matchObj = re.match(pattern, line, re.M|re.I)
  71. if matchObj:
  72. print "matchObj.group() : ", matchObj.group()
  73. print "matchObj.group(1) : ", matchObj.group(1)
  74. print "matchObj.group(2) : ", matchObj.group(2)
  75. else:
  76. print "No match!!"
  77. 2) re.search(pattern, string, flags=0), 扫描整个字符串并返回第一个成功的匹配
  78. import re
  79. pattern = r'(.*) are (.*?) .*'
  80. line = "Cats are smarter than dogs";
  81. searchObj = re.search(pattern, line, re.M|re.I)
  82. if searchObj:
  83. print "searchObj.group() : ", searchObj.group()
  84. print "searchObj.group(1) : ", searchObj.group(1)
  85. print "searchObj.group(2) : ", searchObj.group(2)
  86. else:
  87. print "Nothing found!!"
  88. 3) re.sub(pattern, repl, string, count=0, flags=0), 替换
  89. 参数解释:
  90. pattern : 正则中的模式字符串。
  91. repl : 替换的字符串,也可为一个函数。
  92. string : 要被查找替换的原始字符串。
  93. count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。
  94. import re
  95. phone = "2004-959-559 # 这是一个国外电话号码"
  96. # 删除字符串中的 Python注释
  97. num = re.sub(r'#.*$', "", phone)
  98. print "电话号码是: ", num
  99. # 删除非数字(-)的字符串
  100. num = re.sub(r'\D', "", phone)
  101. print "电话号码是 : ", num
  102. 4) Pattern, 是一个编译好的正则表达式,通过Pattern提供的一系列方法可以对文本进行匹配查找
  103. value = "jason"
  104. line = "jason so cool"
  105. # 获取正则对象
  106. pattern = re.compile(value)
  107. # 检索
  108. match = pattern.search(line)
  109. print match.group(0)

三、数组

  • 列表 (可以修改)
    • 索引
    • 分片
    • 步长
    • 序列运算
    • 成员资格 (是否存在)
    • 函数
    • 操作
  • 元祖 (不能修改)
  • 字典

1、序列

  1. 1.定义序列
  2. 1) 普通定义
  3. edward = ['Edward Gumby',42];
  4. john = ['John Smith',50];
  5. databases = [edward,john];
  6. print databases
  7. [['Edward Gumby', 42], ['John Smith', 50]]
  8. 2.索引
  9. 1) 字符串序列 (字符串就是由字符组成的序列)
  10. greeting = 'Hello'
  11. #从第 0 个索引获取
  12. print greeting[0]
  13. H
  14. #从最后一个索引获取
  15. print greeting[-1]
  16. 3.分片 (边界操作)
  17. code = ['a','b','c','d','e','f','g','h','i','j']
  18. 1) 取索引 3 ~ 6 范围数据
  19. print code[3:6]
  20. ['d', 'e', 'f']
  21. 2) 取索引 3 ~ 最后所有的数据
  22. print code[3:]
  23. ['d', 'e', 'f', 'g', 'h', 'i', 'j']
  24. 3) 取最后索引 -3 ~ 为止,最后的所有数据
  25. print code[-3:]
  26. ['h','i','j']
  27. 4) 取索引 0 - 4 边界的数据
  28. print code[:4]
  29. ['a', 'b', 'c', 'd']
  30. 4) 取索引 0 - max()-1 位置的数据
  31. print code[:-1]
  32. ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
  33. 4.步长 (每次数据指针跳过动的位置,默认 1)
  34. code = ['a','b','c','d','e','f','g','h','i','j']
  35. 1) 默认是步长 1
  36. print code[0:10:1]
  37. ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
  38. 2) 设置步长 3
  39. print code[0:10:3]
  40. ['a', 'd', 'g', 'j']
  41. 5. 序列运算
  42. other = ['st','nd','rd'] + 2 * ['th'] \
  43. + ['st','nd','rd'] + 3 * ['zd']
  44. print other
  45. ['st', 'nd', 'rd', 'th', 'th', 'st', 'nd', 'rd', 'zd', 'zd', 'zd']
  46. 6.成员资格
  47. 1) 是否在序列中
  48. code = ['a','b','c','d','e','f','g','h','i','j']
  49. print 'a' in code
  50. True
  51. print 'z' in code
  52. False
  53. 2) 组合验证
  54. box = [
  55. ['a',123],
  56. ['b',456]
  57. ]
  58. print ['a',123] in box
  59. True
  60. print ['a',8989] in box
  61. False
  62. 7.函数
  63. len() max() min()
  64. 1) len()
  65. numbers = [1,2,3,4,5,6,7,8,9,10]
  66. print len(numbers)
  67. 10
  68. 2) max()
  69. numbers = [1,2,3,4,5,6,7,8,9,10]
  70. print max(numbers)
  71. 10
  72. 3) min()
  73. numbers = [1,2,3,4,5,6,7,8,9,10]
  74. print min(numbers)
  75. 1
  76. print min(1,3,6,8)
  77. 1
  78. list() join()
  79. 1) list() 字符串转数字
  80. arr_hello = list("Hello") ;
  81. print arr_hello
  82. ['H', 'e', 'l', 'l', 'o']
  83. 2) join() 数组转字符串
  84. str_hello = ''.join(arr_hello)
  85. print str_hello
  86. Hello
  87. append() count() extend() index() insert() pop() remove() reverse() sort()
  88. 1) append() 追加对象
  89. code = ['a','b','c','d']
  90. code.append('e')
  91. 2) count() 统计元素在数组出现的次数
  92. code = ['a','b','c','d',[2,3]]
  93. code.count('a')
  94. code.count([2,3])
  95. 3) extend() 在数组尾部追加 1 个或者 n 个值
  96. code = ['a','b','c','d']
  97. code.extend('a')
  98. code.extend([2,3])
  99. 4) index() 找出值所在索引位置
  100. code = ['a','b','c','d']
  101. code.index('b')
  102. 5) insert() 指定位置插入数据
  103. code = ['a','b','c','d']
  104. code.insert(3, 'zzzzz')
  105. 6) pop() 从尾部移除数组值
  106. code = ['a','b','c','d']
  107. code.pop(2)
  108. print code
  109. ['a', 'b', 'd']
  110. 7) remove() 移除匹配的值
  111. code = ['a','b','c','d']
  112. code.remove('b')
  113. 8) reverse() 倒序排序
  114. numbers = [1,3,2,5,4]
  115. numbers.reverse();
  116. print numbers
  117. [4, 5, 2, 3, 1]
  118. 9) sort() 正序排序
  119. numbers = [1,3,2,5,4]
  120. numbers.sort();
  121. print numbers
  122. [1, 2, 3, 4, 5]
  123. 8.操作
  124. 1) 修改元素
  125. code = ['a','b','c','d']
  126. code[0] = 'aaa';
  127. print code
  128. ['aaa', 'b', 'c', 'd']
  129. 2) 删除元素
  130. code = ['a','b','c','d']
  131. del code[2]
  132. print code
  133. ['a', 'b', 'd']
  134. 3) 分片赋值
  135. code = ['a','b','c','d']
  136. code[1:] = list('Hello')
  137. print code
  138. ['a', 'H', 'e', 'l', 'l', 'o']
  139. 4) 替换为空
  140. code = ['a','b','c','d']
  141. code[2:4] = []
  142. print code
  143. ['a', 'b']

2、元祖

  1. 1.普通定义 “,” 逗号很重要(这是标识 元祖的)
  2. code = ('a','b','c','d',)
  3. print code[0]
  4. 2.函数
  5. tuple()
  6. 1) tuple() list() 基本一致,序列转换成元祖
  7. code = ['a','b','c','d']
  8. print tuple(code)
  9. ('a', 'b', 'c', 'd')

3、字典

  1. 1.定义 字典
  2. map_arr = {}
  3. map_arr['a'] = 123;
  4. map_arr['b'] = 456;
  5. print map_arr
  6. 2.查找元素
  7. print map_arr[a]
  8. 3.函数
  9. 1) 长度
  10. print len(map_arr)
  11. 2) 转换成序列、元祖
  12. print map_arr.items()
  13. [('a', 123), ('b', 456)]
  14. 3) map_arr.has_key('a') 验证 key 是否存在
  15. 4) map_arr.get('a') 获取值
  16. 5) map_arr.update({'a':456}) 修改值
  17. 6) map_arr.setdefault({'a':456})
  18. key存在,则覆盖之前的值,若key不存在,则给字典添加key-value
  19. 4. 2 个列表转换为字典
  20. dict(zip(['a','b','c'],[1,2,3]))

四、函数和类

1、函数

  1. 1.定义函数
  2. 1) 普通参数
  3. def fn_test(a,b='a'):
  4. print a
  5. print b
  6. return a;
  7. fn_test(1,2)
  8. 2) *(元祖) 的参数
  9. def test_fn(*args):
  10. print args
  11. print args[0]
  12. #把参数转换为元祖
  13. test_fn(1,2,3,4,6)
  14. 3) **(字典) 的参数
  15. def test_fn(**args):
  16. print args
  17. print args['a']
  18. #把参数转换为字典
  19. test_fn(a='aaa',b='bbb')

2、类

  1. 1. 简单定义
  2. class Test:
  3. def __init__(self,name,age):
  4. self.name = name;
  5. self.age = age;
  6. def echo(self):
  7. return self.name + self.age;
  8. test = Test("a","b");
  9. print test.echo()
  10. 2. 继承
  11. class Apple(Test):
  12. def __init__(self,name,age):
  13. #调用父类方法
  14. Test.__init__(self, name,age)
  15. #重写父类方法
  16. def echo(self):
  17. return self.name + self.age
  18. 3.静态类的方法
  19. class Apple:
  20. @staticmethod
  21. def method():
  22. pass
  23. 访问:Apple.method()

五、模块

1、导入模块

  1. #自定义包路径
  2. global BASE_PATH;
  3. BASE_PATH = os.getcwd();
  4. core_path = BASE_PATH + "/core";
  5. #sys.path.append(core_path);
  6. 1.import model_name
  7. 2.import model_name as model_as_name
  8. model_as_name.function_1()
  9. 3.from model_name import function_1 as fun_as,function_2
  10. (文件名) (类名)
  11. fun_as()
  12. function_2()

2、动态加载模块

  1. package = 'test.test_run'
  2. module = 'TestRun'
  3. importClass = __import__(package, fromlist=[module])
  4. className = getattr(importClass, module)
  5. serviceObject = className()

六、异常

  1. 1. try except 捕获异常
  2. 1) 执行try下的语句,如果引发异常,则执行过程会跳到第一个except语句
  3. 2) 如果第一个except中定义的异常与引发的异常匹配,则执行该except中的语句
  4. 3) 如果引发的异常不匹配第一个except,则会搜索第二个except,允许编写的except数量没有限制
  5. 4) 如果所有的except都不匹配,则异常会传递到下一个调用本代码的最高层try代码中
  6. 5) 如果没有发生异常,则执行else块代码
  7. try:
  8. status = True
  9. except Exception,ex:
  10. print Exception,":",ex
  11. status = False
  12. else:
  13. xx
  14. 2try finally
  15. 1) try 中无论有没有发生异常都要执行代码 finally 下的代码
  16. 2) 如果发生异常,在该异常传递到下一级try时,执行finally中的代码
  17. 3) 如果没有发生异常,则也执行finally中的代码
  18. try:
  19. block
  20. finally:
  21. block