python快速入门
比较方面:变量,字符串,数组,判断,循环,函数 ,命令行参数,时间,文件,数组操作,调试
Python中默认的编码格式是 ASCII 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。
解决方法为只要在文件开头加入 # -*- coding: UTF-8 -*- 或者 #coding=utf-8 就行了
比较项目 | php | python |
变量 | 弱类型语言,变量可以任意代表任何类型 $age = 13; $name = "pengpeng"; $money = 150.53; $isBoy = true;
这里等号前后空格是为了整齐好看。
例子 <?php $age = 13; print $age; ?> 运行方式 php t.php | 弱类型语言 counter = 100 # 赋值整型变量 miles = 1000.0 # 浮点型 name = "John" # 字符串
例子
#!/usr/bin/python # -*- coding: UTF-8 -*- counter = 100 # 赋值整型变量 miles = 1000.0 # 浮点型 name = "John" # 字符串 print counter print miles print name
命令运行方式 python test.py |
字符串及连接 | $str1 = "str1"; $str2 = "str2"; $str3 = $str1.$str2; $str4 = $str1."test".$str2; print $str3."\n"; print $str4."\n"; | 加号(+)是字符串连接运算符,星号(*)是重复操作。如下实例: str = 'Hello World!' print str # 输出完整字符串 print str[0] # 输出字符串中的第一个字符 print str[2:5] # 输出字符串中第三个至第五个之间的字符串 print str[2:] # 输出从第三个字符开始的字符串 print str * 2 # 输出字符串两次 print str + "TEST" # 输出连接的字符串
|
数组遍历 | <?php $colorArr = array('red','blue','green','yellow'); foreach ($colorArr as $color){ print $color."\n"; } ?> |
list1 = ['item1', 'item2', 'item3'] for item in list1: print(item)
|
哈希数组及遍历 | <?php $ageArr = array('zhang'=>13,'li'=>14,'wang'=>15,'qian'=>12); foreach ($ageArr as $name => $age){ print "$name = $age\n"; } ?> | #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print "dict['Name']: ", dict['Name'] print "dict['Age']: ", dict['Age']
a = {'a': '1', 'b': '2', 'c': '3'} for key in a.keys(): print(key+':'+a[key]) for value in a.values(): print(value) |
json | $arr = Array('one', 'two', 'three'); echo json_encode($arr);
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
| json.dumps json.dumps 用于将 Python 对象编码成 JSON 字符串。
#!/usr/bin/python import json
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
jsonObj = json.dumps(data) print jsonObj ==================================================================== json.loads json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。
#!/usr/bin/python import json
jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
text = json.loads(jsonData) print text |
条件判断 | <?php $user=`whoami`; if($user != "work" || ! isset($argv[1]) ) { echo "必须是work账户,同时为./release.sh snake 或者 ./release.sh hornbill"; exit ; } else { echo "no problem"; }
?> |
#!/usr/bin/python # -*- coding: UTF-8 -*- # 例2:elif用法 num = 5 if num == 3: # 判断num的值 print 'boss' elif num == 2: print 'user' elif num == 1: print 'worker' elif num < 0: # 值小于零时输出 print 'error' else: print 'roadman' # 条件均不成立时输出 |
case | case $1 in "snake") back_snake; snake; reduction_snakenx; other_snake; virus_restart; ;; "hornbill") back_hornbill; hornbill; # hornbill_min; # hornbill_restart; reduction_nx; other_hornbill; hornbill_restart_again; ;; "backup") back_snake; back_hornbill; hornbill_restart; exit; ;; *) echo NULL; ;; esac
希望函数 back_snake 往后变为 backSnake | 无 |
循环 | <?php for($i=0;$i<10;$i++) { print $i."\n"; } ?> | #!/usr/bin/python # -*- coding: UTF-8 -*- for letter in 'Python': # 第一个实例 print '当前字母 :', letter fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # 第二个实例 print '当前水果 :', fruit |
函数定义
或 方法定义 | <?php header ( "Content-Type:text/html;charset=utf-8" ); function send_content_mail($maillist, $subject, $content) { $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=utf-8" . "\r\n"; $headers .= 'From: stat@meilishuo.com' . "\r\n"; $subject = "=?UTF-8?B?" . base64_encode($subject) . "?="; $content.="<center>如有疑问,咨询管理员曾文杰wenjiezeng@meilishuo.com</center"; mail($maillist, $subject, $content, $headers); }
send_content_mail("wenjiezeng@meilishuo.com", "test", "testMail"); ?> | #!/usr/bin/python # -*- coding: UTF-8 -*- # 定义函数 def printme( str ): "打印任何传入的字符串" print str; return; # 调用函数 printme("我要调用用户自定义函数!"); printme("再次调用同一函数"); |
命令行参数 | $argv <?php print_r($argv); ?>
php t.php 1 2 3 Array ( [0] => t.php [1] => 1 [2] => 2 [3] => 3 ) | #!/usr/bin/python # -*- coding: UTF-8 -*-
import sys fileName = sys.argv[0] print '参数个数为:', len(sys.argv), '个参数。' print '参数列表:', str(sys.argv) print '文件:', fileName |
时间处理 | date_default_timezone_set('PRC'); $today = date("Y-m-d",time()); $yesterday = date("Y-m-d",time()-86400); $yesterday = date("Ymd",strtotime("-1 day")); | #!/usr/bin/python # -*- coding: UTF-8 -*- import datetime today = datetime.date.today() print today.strftime("%Y-%m-%d %H:%M:%S")
def getYesterday(): today=datetime.date.today() oneday=datetime.timedelta(days=1) yesterday=today-oneday return yesterday yesterday = getYesterday() print yesterday.strftime("%Y-%m-%d %H:%M:%S")
|
小文件 切行处理 | $cc = file_get_contents($file); $tmpArr = preg_split('/\r|\n/',$cc,-1,PREG_SPLIT_NO_EMPTY); foreach($tmpArr as $line) { //do with $line } | #!/usr/bin/python # -*- coding: UTF-8 -*- import re file_object = open('thefile.txt') try: all_the_text = file_object.read( ) ##print all_the_text lines = re.split( '\r|\n', all_the_text) for item in lines: print("line="+item) finally: file_object.close( )
|
大文件逐行 | <?php $handle = @fopen("/tmp/inputfile.txt", "r"); if ($handle) { while (!feof($handle)) { $buffer = fgets($handle, 4096); echo $buffer; } fclose($handle); } ?> | #!/usr/bin/python # -*- coding: UTF-8 -*- import re f = open("thefile.txt") # 返回一个文件对象 line = f.readline() # 调用文件的 readline()方法 while line: print line, # 后面跟 ',' 将忽略换行符 line = f.readline() #再读取一行 f.close()
|
数组函数 | arsort() asort() count() krsort() ksort() | #!/usr/bin/python # -*- coding: UTF-8 -*- ls = list([5, 2, 3, 1, 4]) new_ls = sorted(ls) print(new_ls)
|
调试函数 | var_dump() print_r() | #!/usr/bin/python # -*- coding: UTF-8 -*- def dump(obj): '''return a printable representation of an object for debugging''' newobj=obj if '__dict__' in dir(obj): newobj=obj.__dict__ if ' object at ' in str(obj) and not newobj.has_key('__type__'): newobj['__type__']=str(obj) for attr in newobj: newobj[attr]=dump(newobj[attr]) return newobj ls = list([5, 2, 3, 1, 4]) obj=dump(ls) print(dump(obj)) |
字符替换 | $file = preg_replace('/\.less$/','.css',$file); | 1用字符串本身的replace方法:
a = 'hello word' b = a.replace('word','python') print b 2用正则表达式来完成替换:
import re a = 'hello word' b = re.sub('word','python', a) print b |
发送邮件 | | #!/usr/bin/python # -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.header import Header sender = 'from@runoob.com' receivers = ['429240967@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 # 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码 message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8') message['From'] = Header("菜鸟教程", 'utf-8') # 发送者 message['To'] = Header("测试", 'utf-8') # 接收者 subject = 'Python SMTP 邮件测试' message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message.as_string()) print "邮件发送成功" except smtplib.SMTPException: print "Error: 无法发送邮件" |