标签:python
VII Python(2)基础知识
list举例:
[root@localhost ~]# vim using_list.py
--------------scriptstart------------------
#!/usr/bin/python
#filename:using_list.py
shoplist=[‘apple‘,‘mango‘,‘carrot‘,‘banana‘]
print ‘I have‘,len(shoplist),‘items topurchase.‘
print ‘these items are:‘,
for item in shoplist:
print item,
print ‘\nI also have to buy rice.‘
shoplist.append(‘rice‘)
print ‘My shoplist is now‘,shoplist
print ‘I will sort my list now.‘
shoplist.sort()
print ‘sorted shopping list is‘,shoplist
print ‘the first item I will buyis‘,shoplist[0]
olditem=shoplist[0]
del shoplist[0]
print ‘I bought the‘,olditem
print ‘my shoplist is now‘,shoplist
--------------script end-------------------
[root@localhost ~]# python using_list.py
I have 4 items to purchase.
these items are: apple mango carrot banana
I also have to buy rice.
My shoplist is now [‘apple‘, ‘mango‘,‘carrot‘, ‘banana‘, ‘rice‘]
I will sort my list now.
sorted shopping list is [‘apple‘, ‘banana‘,‘carrot‘, ‘mango‘, ‘rice‘]
the first item I will buy is apple
I bought the apple
my shoplist is now [‘banana‘, ‘carrot‘,‘mango‘, ‘rice‘]
tuple举例:
[root@localhost ~]# vim using_tuple.py
------------------scriptstart----------------
#!/usr/bin/python
#filename:using_tuple.py
zoo=(‘wolf‘,‘elephant‘,‘penguin‘)
print ‘number of animals in he zoois‘,len(zoo)
new_zoo=(‘monkey‘,‘dolphin‘,zoo)
print ‘number of animals in the new zoois‘,len(new_zoo)
print ‘all animals in the new_zooare‘,new_zoo
print ‘animals brought from old zooare‘,new_zoo[2]
print ‘last animals brought from old zoois‘,new_zoo[2][2]
---------------script end------------------
[root@localhost ~]# python using_tuple.py
number of animals in he zoo is 3
number of animals in the new zoo is 3
all animals in the new_zoo are (‘monkey‘,‘dolphin‘, (‘wolf‘, ‘elephant‘, ‘penguin‘))
animals brought from old zoo are (‘wolf‘,‘elephant‘, ‘penguin‘)
last animals brought from old zoo ispenguin
dictionary举例:
[root@localhost ~]# vim using_dictionary.py
-------------------scriptstart--------------
#!/usr/bin/python
#filename:using_dictionary.py
ab={‘jowin‘:‘jowin@163.com‘,
‘xiang‘:‘xiang@qq.com‘,
‘matsumoto‘:‘matsumoto@ruby-lang.org‘,
‘spammer‘:‘spammer@hotmail.com‘
}
print "jowin‘s address is %s" %ab[‘jowin‘]
ab[‘guido‘]=‘guido@python.org‘
del ab[‘jowin‘]
print ‘\nthere are %d contacts in theaddress-book\n‘ % len(ab)
for name,address in ab.items():
print ‘contact %s at %s‘ % (name,address)
if ‘guido‘ in ab:
print "\nguido‘s address is %s" % ab[‘guido‘]
------------------scriptend--------------------
[root@localhost ~]# pythonusing_dictionary.py
jowin‘s address is jowin@163.com
there are 4 contacts in the address-book
contact matsumoto atmatsumoto@ruby-lang.org
contact xiang at xiang@qq.com
contact spammer at spammer@hotmail.com
contact guido at guido@python.org
guido‘s address is guido@python.org
序列(list、tuple、字符串都是序列,序列的两个主要特点:索引index操作符(可获得一个特定条目)和切片split操作符(可获得一部分条目))
序列的神奇之处在于可用相同的方法访问tuple、list、字符串
序列举例:
[root@localhost ~]# vim seq.py
------------------scriptstart-------------------
#!/usr/bin/python
#filename:seq.py
shoplist=[‘apple‘,‘mango‘,‘carrot‘,‘banana‘]
print ‘item 0 is‘,shoplist[0]
print ‘item 3 is‘,shoplist[3]
print ‘item -1 is‘,shoplist[-1]
print ‘item -2 is‘,shoplist[-2]
print ‘item 1 to 3 is‘,shoplist[1:3]
print ‘item 2 to end is‘,shoplist[2:]
print ‘item start to end is‘,shoplist[:]
name=‘jowin‘
print ‘characters 1 to 3 is‘,name[1:3]
print ‘characters 2 to end is‘,name[2:]
print ‘characters start to end is‘,name[:]
-------------------scriptend---------------
[root@localhost ~]# python seq.py
item 0 is apple
item 3 is banana
item -1 is banana
item -2 is carrot
item 1 to 3 is [‘mango‘, ‘carrot‘]
item 2 to end is [‘carrot‘, ‘banana‘]
item start to end is [‘apple‘, ‘mango‘,‘carrot‘, ‘banana‘]
characters 1 to 3 is ow
characters 2 to end is win
characters start to end is jowin
参考(当创建一个对象并给它赋一个变量时,这个变量仅仅参考那个对象,而不是表示这个对象本身,这称作名称到对象的绑定,变量名是指向存储那个对象的内存,若要复制list、tuple或类似的序列或其它复杂的对象,必须使用切片操作符,若只是想要使用另一个变量名,两个名称都可参考同一个对象)
注:列表的赋值语句不创建拷贝,得使用切换操作符创建序列的拷贝
参考举例:
[root@localhost ~]# vim reference.py
--------------------scriptstart---------------------
#!/usr/bin/python
#filename:reference.py
print ‘simple assignment‘
shoplist=[‘apple‘,‘mango‘,‘carrot‘,‘banana‘]
mylist=shoplist
del shoplist[0]
print ‘shoplist is‘,shoplist
print ‘mylist is‘,mylist
print ‘copy by making a full slice‘
mylist=shoplist[:]
del mylist[0]
print ‘shoplist is‘,shoplist
print ‘mylist is‘,mylist
-------------------scriptend--------------------------
[root@localhost ~]# python reference.py
simple assignment
shoplist is [‘mango‘, ‘carrot‘, ‘banana‘]
mylist is [‘mango‘, ‘carrot‘, ‘banana‘]
copy by making a full slice
shoplist is [‘mango‘, ‘carrot‘, ‘banana‘]
mylist is [‘carrot‘, ‘banana‘]
更多字符串内容(字符串也是对象,同样具有方法(可检验一部分字符串,去除空格等各种工作),程序中使用的字符串都是str类的对象)
方法(startswith(测试字符串是否以给定的字符串开始);find(找出给定字符串在另一字符串的位置);‘DELIMETER‘.join(分隔符字符串join序列可整洁输出))
字符串举例:
[root@localhost ~]# vim str_methods.py
----------------scriptstart--------------------
#!/usr/bin/python
#filename:str_methods.py
name=‘jowin‘
if name.startswith(‘jow‘):
print ‘yes,the string startswith "jow"‘
if ‘w‘ in name:
print ‘yes,it conatains the string "w"‘
if name.find(‘win‘)!=-1:
print ‘yes,it contains the string "win"‘
delimeter=‘_*_‘
mylist=[‘Brazil‘,‘Russia‘,‘India‘,‘China‘]
print delimeter.join(mylist)
----------------scriptend---------------------
[root@localhost ~]# python str_methods.py
yes,the string startswith "jow"
yes,it conatains the string "w"
yes,it contains the string "win"
Brazil_*_Russia_*_India_*_China
备份脚本举例:
os.sep(会根据OS给出目录分隔符,如linux为"/",win为"\",mac为":",使用os.sep有利于程序移植)
time.strftime(‘%Y%m%d‘)(格式化时间输出)
下例给出三个版本,先完成基本功能再逐步优化,还可以进一步优化(可用tar命令的-X选项将某文件排除在外,tar代替zip使备份更快更小;最好使用zipfile和tarfile这是python标准库的一部分,不推荐使用os.system函数容易引发严重错误;使用-v使程序更具交互性;sys.argv使文件和目录通过命令行直接传递给脚本)
[root@localhost ~]# vim backup_ver1.py
----------------script start---------------
#!/usr/bin/python
#filename:backup_ver1.py(优化文件名,用日期作为目录名,用时间作为文件名)
import os,time
source=[‘/home/webgame/houtai‘,‘/usr/local/servernd‘]
target_dir=‘/backup/‘
target=target_dir+time.strftime(‘%Y%m%d-%H%M%S‘)+‘.zip‘
zip_command="zip -qr ‘%s‘ %s" %(target,‘ ‘.join(source))
if os.system(zip_command)==0:
print ‘successful backup to‘,target
else:
print ‘backup failed‘
-----------------script end----------------
[root@localhost ~]# python backup_ver1.py
successful backup to /backup/20160523-000610.zip
[root@localhost ~]# ll /backup/
total 4
-rw-r--r--. 1 root root 356 May 23 00:0620160523-000610.zip
[root@localhost ~]# vim backup_ver2.py
-----------------scriptstart-----------------
#!/usr/bin/python
#filename:backup_ver2.py
import os,time
source=[‘/home/webgame/houtai‘,‘/usr/local/servernd‘]
target_dir=‘/backup/‘
today=target_dir+time.strftime(‘%Y%m%d‘)
now=time.strftime(‘%H%M%s‘)
if not os.path.exists(today):
os.mkdir(today)
print ‘successfully created directory‘,today
target=today+os.sep+now+‘.zip‘
zip_command="zip -qr ‘%s‘ %s" %(target,‘ ‘.join(source))
if os.system(zip_command)==0:
print ‘successfully backup to‘,target
else:
print ‘backup failed‘
-----------------scritp end----------------
[root@localhost ~]# python backup_ver2.py
successfully created directory/backup/20160523
successfully backup to/backup/20160523/002721.zip
[root@localhost ~]# vim backup_ver3.py
----------------scriptstart------------------
#!/usr/bin/python
#filename:backup_ver3.py(优化可添加注释信息)
import os,time
source=[‘/home/webgame/houtai‘,‘/usr/local/servernd‘]
target_dir=‘/backup/‘
today=target_dir+time.strftime(‘%Y%m%d‘)
now=time.strftime(‘%H%M%S‘)
comment=raw_input(‘Enter a comment-->‘)
if len(comment)==0:
target=today+os.sep+now+‘.zip‘
else:
target=today+os.sep+now+‘_‘+comment.replace(‘ ‘,‘_‘)+‘.zip‘
if not os.path.exists(today):
os.mkdir(today)
print ‘successfully created directory‘,today
zip_command=‘zip -qr "%s" %s‘ %(target,‘ ‘.join(source))
if os.system(zip_command)==0:
print ‘successfully backup to‘,target
else:
print ‘backup failed‘
------------------scriptend--------------------
[root@localhost ~]# python backup_ver3.py
Enter a comment-->test
successfully backup to/backup/20160523/002950_test.zip
本文出自 “Linux运维重难点学习笔记” 博客,请务必保留此出处http://jowin.blog.51cto.com/10090021/1782169
标签:python
原文地址:http://jowin.blog.51cto.com/10090021/1782169