这是我见过最完整的Python语法和实战清单!是个人都能看懂学会!

基础语法

Python 是一门高阶、动态类型的多范式编程语言;定义 Python 文件的时候我们往往会先声明文件编码方式:

# 指定脚本调用方式
#!/usr/bin/env python
# 配置 utf-8 编码
# -*- coding: utf-8 -*-
# 配置其他编码
# -*- coding:  -*-
# Vim 中还可以使用如下方式
# vim:fileencoding=

人生苦短,请用 Python,大量功能强大的语法糖的同时让很多时候 Python 代码看上去有点像伪代码。譬如我们用 Python 实现的简易的快排相较于 Java 会显得很短小精悍:

def quicksort(arr):
 if len(arr) <= 1:
 return arr
 pivot = arr[len(arr) / 2]
 left = [x for x in arr if x < pivot]
 middle = [x for x in arr if x == pivot]
 right = [x for x in arr if x > pivot]
 return quicksort(left) + middle + quicksort(right)
print quicksort([3,6,8,10,1,2,1])
# Prints "[1,3,10]"进群:548377875  

控制台交互

可以根据 __name__ 关键字来判断是否是直接使用 python 命令执行某个脚本,还是外部引用;Google 开源的 fire 也是不错的快速将某个类封装为命令行工具的框架:

import fire
class Calculator(object):
 """A simple calculator class."""
 def double(self,number):
 return 2 * number
if __name__ == '__main__':
 fire.Fire(Calculator)
# python calculator.py double 10 # 20
# python calculator.py double --number=15 # 30

Python 2 中 print 是表达式,而 Python 3 中 print 是函数;如果希望在 Python 2 中将 print 以函数方式使用,则需要自定义引入:

from __future__ import print_function

我们也可以使用 pprint 来美化控制台输出内容:

import pprint
stuff = ['spam','eggs','lumberjack','knights','ni']
pprint.pprint(stuff)
# 自定义参数
pp = pprint.PrettyPrinter(depth=6)
tup = ('spam',('eggs',('lumberjack',('knights',('ni',('dead',('parrot',('fresh fruit',))))))))
pp.pprint(tup)

模块

Python 中的模块(Module)即是 Python 源码文件,其可以导出类、函数与全局变量;当我们从某个模块导入变量时,函数名往往就是命名空间(Namespace)。而 Python 中的包(Package)则是模块的文件夹,往往由 __init__.py 指明某个文件夹为包:

# 文件目录
someDir/
 main.py
 siblingModule.py
# siblingModule.py
def siblingModuleFun():
 print('Hello from siblingModuleFun')
def siblingModuleFunTwo():
 print('Hello from siblingModuleFunTwo')
import siblingModule
import siblingModule as sibMod
sibMod.siblingModuleFun()
from siblingModule import siblingModuleFun
siblingModuleFun()
try:
 # Import 'someModuleA' that is only available in Windows
 import someModuleA
except ImportError:
 try:
 # Import 'someModuleB' that is only available in Linux
 import someModuleB
 except ImportError:

Package 可以为某个目录下所有的文件设置统一入口:

someDir/
 main.py
 subModules/
 __init__.py
 subA.py
 subSubModules/
 __init__.py
 subSubA.py
# subA.py
def subAFun():
 print('Hello from subAFun')
def subAFunTwo():
 print('Hello from subAFunTwo')
# subSubA.py
def subSubAFun():
 print('Hello from subSubAFun')
def subSubAFunTwo():
 print('Hello from subSubAFunTwo')
# __init__.py from subDir
# Adds 'subAFun()' and 'subAFunTwo()' to the 'subDir' namespace 
from .subA import *
# The following two import statement do the same thing,they add 'subSubAFun()' and 'subSubAFunTwo()' to the 'subDir' namespace. The first one assumes '__init__.py' is empty in 'subSubDir',and the second one,assumes '__init__.py' in 'subSubDir' contains 'from .subSubA import *'.
# Assumes '__init__.py' is empty in 'subSubDir'
# Adds 'subSubAFun()' and 'subSubAFunTwo()' to the 'subDir' namespace
from .subSubDir.subSubA import *
# Assumes '__init__.py' in 'subSubDir' has 'from .subSubA import *'
# Adds 'subSubAFun()' and 'subSubAFunTwo()' to the 'subDir' namespace
from .subSubDir import *
# __init__.py from subSubDir
# Adds 'subSubAFun()' and 'subSubAFunTwo()' to the 'subSubDir' namespace
from .subSubA import *
# main.py
import subDir
subDir.subAFun() # Hello from subAFun
subDir.subAFunTwo() # Hello from subAFunTwo
subDir.subSubAFun() # Hello from subSubAFun
subDir.subSubAFunTwo() # Hello from subSubAFunTwo

表达式与控制流

条件选择

Python 中使用 if、elif、else 来进行基础的条件选择操作:

if x < 0:
 x = 0
 print('Negative changed to zero')
 elif x == 0:
 print('Zero')
 else:
 print('More')

Python 同样支持 ternary conditional operator:

a if condition else b

也可以使用 Tuple 来实现类似的效果:

# test 需要返回 True 或者 False
(falseValue,trueValue)[test]
# 更安全的做法是进行强制判断
(falseValue,trueValue)[test == True]
# 或者使用 bool 类型转换函数
(falseValue,trueValue)[bool()]

进行强制判断(falseValue,trueValue)[test == True]# 或者使用 bool 类型转换函数(falseValue,trueValue)[bool()]

循环遍历

for-in 可以用来遍历数组与字典:

words = ['cat','window','defenestrate']
for w in words:
 print(w,len(w))
# 使用数组访问操作符,能够迅速地生成数组的副本
for w in words[:]:
 if len(w) > 6:
 words.insert(0,w)
# words -> ['defenestrate','cat','defenestrate']

如果我们希望使用数字序列进行遍历,可以使用 Python 内置的 range 函数:

a = ['Mary','had','a','little','lamb']
for i in range(len(a)):
 print(i,a[i])

基本数据类型

可以使用内建函数进行强制类型转换(Casting):

int(str)
float(str)
str(int)
str(float)

Number: 数值类型

x = 3
print type(x) # Prints ""
print x # Prints "3"
print x + 1 # Addition; prints "4"
print x - 1 # Subtraction; prints "2"
print x * 2 # Multiplication; prints "6"
print x ** 2 # Exponentiation; prints "9"
x += 1
print x # Prints "4"
x *= 2
print x # Prints "8"
y = 2.5
print type(y) # Prints ""
print y,y + 1,y * 2,y ** 2 # Prints "2.5 3.5 5.0 6.25"

布尔类型

Python 提供了常见的逻辑操作符,不过需要注意的是 Python 中并没有使用 &&、|| 等,而是直接使用了英文单词。

t = True
f = False
print type(t) # Prints ""
print t and f # Logical AND; prints "False"
print t or f # Logical OR; prints "True"
print not t # Logical NOT; prints "False"
print t != f # Logical XOR; prints "True" 

String: 字符串

Python 2 中支持 Ascii 码的 str() 类型,独立的 unicode() 类型,没有 byte 类型;而 Python 3 中默认的字符串为 utf-8 类型,并且包含了 byte 与 bytearray 两个字节类型:

type("Guido") # string type is str in python2
# 
# 使用 __future__ 中提供的模块来降级使用 Unicode
from __future__ import unicode_literals
type("Guido") # string type become unicode
# 

Python 字符串支持分片、模板字符串等常见操作:

var1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ",var1[0]
print "var2[1:5]: ",var2[1:5]
# var1[0]: H
# var2[1:5]: ytho
print "My name is %s and weight is %d kg!" % ('Zara',21)
# My name is Zara and weight is 21 kg!
str[0:4]
len(str)
string.replace("-"," ")
",".join(list)
"hi {0}".format('j')
str.find(",")
str.index(",") # same,but raises IndexError
str.count(",")
str.split(",")
str.lower()
str.upper()
str.title()
str.lstrip()
str.rstrip()
str.strip()
str.islower()
# 移除所有的特殊字符
re.sub('[^A-Za-z0-9]+','',mystring) 

如果需要判断是否包含某个子字符串,或者搜索某个字符串的下标:

# in 操作符可以判断字符串
if "blah" not in somestring: 
 continue
# find 可以搜索下标
s = "This be a string"
if s.find("is") == -1:
 print "No 'is' here!"
else:
 print "Found 'is' in the string."

Regex: 正则表达式

import re
# 判断是否匹配
re.match(r'^[aeiou]',str)
# 以第二个参数指定的字符替换原字符串中内容
re.sub(r'^[aeiou]','?',str)
re.sub(r'(xyz)',r'',str)
# 编译生成独立的正则表达式对象
expr = re.compile(r'^...$')
expr.match(...)
expr.sub(...)

下面列举了常见的表达式使用场景:

# 检测是否为 HTML 标签
re.search('<[^/>][^>]*>','

集合类型

List: 列表

Operation: 创建增删

list 是基础的序列类型:

l = []
l = list()
# 使用字符串的 split 方法,可以将字符串转化为列表
str.split(".")
# 如果需要将数组拼装为字符串,则可以使用 join 
list1 = ['1','2','3']
str1 = ''.join(list1)
# 如果是数值数组,则需要先进行转换
list1 = [1,3]
str1 = ''.join(str(e) for e in list1)

可以使用 append 与 extend 向数组中插入元素或者进行数组连接

x = [1,3]
x.append([4,5]) # [1,[4,5]]
x.extend([4,4,5],注意 extend 返回值为 None

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。