VII Python (2) Basics

Source: Internet
Author: User

VII Python ( 2 ) Basic Knowledge

List Examples:

[Email protected] ~]# 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 has to buy rice. '

Shoplist.append (' rice ')

print ' My shoplist is now ', shoplist

print ' I'll sort my list now. '

Shoplist.sort ()

print ' sorted shopping list is ', shoplist

print ' The first item I'll buyis ', shoplist[0]

OLDITEM=SHOPLIST[0]

Del Shoplist[0]

print ' I bought the ', Olditem

print ' My shoplist is now ', shoplist

--------------Script End-------------------

[email protected] ~]# python using_list.py

I have 4 items to purchase.

These items are:apple Mango carrot Banana

I also has to buy rice.

My shoplist is now [' Apple ', ' mango ', ' carrot ', ' banana ', ' rice ']

I'll sort my list now.

Sorted shopping list is [' Apple ', ' banana ', ' carrot ', ' mango ', ' rice ']

The first item I'll buy is Apple

I bought the apple

My shoplist is now [' banana ', ' carrot ', ' mango ', ' rice ']

Examples of tuple :

[Email protected] ~]# 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 the old Zooare ', new_zoo[2]

print ' Last animals brought from old Zoois ', new_zoo[2][2]

---------------Script End------------------

[email protected] ~]# 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 is (' Monkey ', ' Dolphin ', (' Wolf ', ' Elephant ', ' penguin ')

Animals brought from the old Zoo is (' Wolf ', ' Elephant ', ' penguin ')

Last animals brought from the old zoo Ispenguin

Dictionary Example:

[Email protected] ~]# vim using_dictionary.py

-------------------Scriptstart--------------

#!/usr/bin/python

#filename: using_dictionary.py

ab={' Jowin ': ' [email protected] ',

' Xiang ': ' [email protected] ',

' Matsumoto ': ' [email protected] ',

' Spammer ': ' [email protected] '

}

Print "Jowin s address is%s"%ab[' Jowin ']

ab[' Guido ']= ' [email protected] '

Del ab[' Jowin ']

print ' \nthere is%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--------------------

[Email protected] ~]# pythonusing_dictionary.py

Jowin ' s address is [email protected]

There is 4 contacts in the Address-book

Contact Matsumoto [email protected]

Contact Xiang at [email protected]

Contact spammer at [email protected]

Contact Guido at [email protected]

Guido ' s address is [email protected]

sequence (list,tuple, string are sequences, two main features of the sequence: indexed index operator (can get a specific entry) and slice split Operator (partial entry is available))

the magic of a sequence is that you can access a tuple,list, string in the same way

Sequence Examples:

[Email protected] ~]# 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 ', Shoplist[2:]

print ' item start to end ', shoplist[:]

Name= ' Jowin '

print ' characters 1 to 3 ', Name[1:3]

print ' characters 2 to end ', Name[2:]

print ' characters start to end ', name[:]

-------------------Scriptend---------------

[email protected] ~]# 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 are win

Characters start to end is Jowin

reference (when creating an object and assigning it a variable, this variable only references that object, not the object itself, which is called the name-to-object binding, the variable name is to the memory that stores that object, to copy the list,tuple or similar sequences or other complex objects, you must use the slice operator, if you just want to use another variable name, two names can refer to the same object)

Note: The assignment statement for the list does not create a copy, and the switch operator is used to create a copy of the sequence

Reference examples:

[Email protected] ~]# 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--------------------------

[email protected] ~]# 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 ']

More string content (string is also an object, also has a method (can examine a part of the string, remove whitespace and other work), the string used in the program is the STR class object)

method (startswith(tests whether a string starts with a given string);Find(Find out where the given string is in another string);' Delimeter '. Join(delimiter string the join sequence can be neatly output))

Examples of strings:

[Email protected] ~]# 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---------------------

[email protected] ~]# 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

Examples of backup scripts:

OS.SEP (the directory delimiter is givenbased on the OS , such as Linux as "/",win for "\",mac as ":" ) , using OS.SEP to facilitate program porting)

Time.strftime ('%y%m%d ') (formatted time output)

The following example gives three versions, the first to complete the basic functions and then gradually optimize, but also can be further optimized ( using the- x option of the TAR command to exclude a file,tar instead of zip to make backup faster and smaller ; it's best to use ZipFile and tarfile. This is part of the Python standard library and it is not recommended to use the Os.system function to cause serious errors; Use -v Make the program more interactive;sys.argv make files and directories pass directly to the script through the command line)

[Email protected] ~]# vim backup_ver1.py

----------------Script Start---------------

#!/usr/bin/python

#filename: backup_ver1.py(optimize file name, use date as directory name, time as filename)

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----------------

[email protected] ~]# python backup_ver1.py

Successful backup To/backup/20160523-000610.zip

[Email protected] ~]# ll/backup/

Total 4

-rw-r--r--. 1 root root 356 may 00:0620160523-000610.zip

[Email protected] ~]# 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----------------

[email protected] ~]# python backup_ver2.py

Successfully created directory/backup/20160523

Successfully backup To/backup/20160523/002721.zip

[Email protected] ~]# vim backup_ver3.py

----------------Scriptstart------------------

#!/usr/bin/python

#filename: backup_ver3.py(optimized to add annotation information)

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--------------------

[email protected] ~]# python backup_ver3.py

Enter a Comment-->test

Successfully backup To/backup/20160523/002950_test.zip


This article is from the "Linux Operational Difficulty Learning notes" blog, please be sure to keep this source http://jowin.blog.51cto.com/10090021/1782169

VII Python (2) Basics

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.