Python full-stack Development 7. Module and several common modules and format knowledge supplement, pythonformat

Source: Internet
Author: User
Tags timestamp to date

Python full-stack Development 7. Module and several common modules and format knowledge supplement, pythonformat
I. Module Classification

One of the reasons for the popularity of Python is that it has a large number of third-party modules, so we don't have to re-create the wheel from scratch when writing code. Many of the functions to use have been written and encapsulated into libraries, we only need to call it directly. modules are divided into built-in modules, custom modules, and installed third-party modules, which are generally placed in different places. Next, let's take a look at how to import the built-in modules, and where they are stored.

Import sys # You can use import to directly import the built-in module for I in sys. path: # sys. path stores the path print (I) '''c: \ Users \ Tab \ AppData \ Local \ Programs \ Python \ Python35 \ python.exe C: /Users/Tab/PycharmProjects/modules/1.pyc:\ Users \ Tab \ PycharmProjects \ modules C: \ Users \ Tab \ PycharmProjects \ modules # Place the custom module in the current workspace C: \ Users \ Tab \ AppData \ Local \ Programs \ Python \ Python35 \ python35.zipC: \ Users \ Tab \ AppData \ Local \ Programs \ Python \ Python35 \ DLLsC: \ Users \ Tab \ AppData \ Local \ Programs \ Python \ Python35 \ lib # storage location of the built-in Module C: \ Users \ Tab \ AppData \ Local \ Programs \ Python \ Python35C: \ Users \ Tab \ AppData \ Local \ Programs \ Python \ Python35 \ lib \ site-packages # Third-Party Library installation location ''' # sys. use the append () method to import data in path, for example, sys. path. after append ('d: '), you can use import to directly import The py file in the D: directory to print (sys. platform) # win32 sys. platform can obtain the current working platform (win32) or linux # In addition, sys. argv can obtain the Script Parameters. argv [0] is the script name, And argv [1] is the first parameter...
Ii. Module Import

First, you must note that the names of the modules defined by yourself are different from those of the built-in modules. Otherwise, problems may occur during import. the built-in modules and third-party modules already have sys. in the path of the path, you can directly import it. The following describes how to import a project and the libraries in the project. Suppose I have defined a modules project, the following shows the directory structure. py file Import

    

On the left is the directory tree, and on the right is the function defined under lib/account. py in the 1. py file, which lists three common import methods.

Iii. OS Module

The OS module is a module related to the operating system. For example, operating on files and directories and obtaining paths can all be implemented by the OS module. The OS module provides too many functions, next, let's take a look at the common usage.

Import osprint (OS. getcwd () # C: \ Users \ Tab \ PycharmProjects \ modules get current job path print (OS. environ) # obtain the system environment variable print (OS. getenv ('path') # obtain the OS OF THE PATH environment variable. mkdir ('test') # create a test directory OS in the current workspace. remove ('path/to/file') # delete the file OS. rmdir ('test') # Delete the 'test' directory print (OS. stat ('1. py ') # returns the detailed information about the file OS. stat_result (st_mode = 33206... st_nlink = 1, st_uid = 0, st_gid = 0, st_size = 3152 ...) print (OS. path. basename (r 'C: \ Users \ Tab \ PycharmProjects \ modules \ 1. py ') # Get the file name in the Path 1. pyprint (OS. path. abspath ('1. py ') # obtain the absolute path of the file C: \ Users \ Tab \ PycharmProjects \ modules \ 1. pyprint (OS. path. dirname (r'c: \ Users \ Tab \ PycharmProjects \ modules \ 1. py ') # obtain the path name print (OS. path. split (r 'C: \ Users \ Tab \ PycharmProjects \ modules \ 1. py ') # split the file and path print (OS. path. join (r 'C: \ Users \ Tab \ PycharmProjects \ Les ', '1. py ') # merge path
Iv. hashlib Module

Hashlib is an encryption module that provides common encryption algorithms, such as MD5, SHA1, and SHA256. It converts data of any length into a fixed-length data string through a function, it is often used to save passwords. For example, after the user's password is encrypted with MD5, it is saved to the database. When a user logs on, it calculates the MD5 of the plaintext password entered by the user, and then compares it with the MD5 of the database storage, if they are consistent, the password is entered correctly. If they are inconsistent, the password is definitely incorrect. Next let's take a look at the usage

Import hashlibpasswd = hashlib. sha256 () passwd. update (bytes ('100', encoding = 'utf-8') # assume that the password is 123456 to convert it to a byte and pass in the print (passwd. hexdigest () # digest = hashlib. sha256 (bytes ('wxtrkbc', encoding = 'utf-8') # Add a complex string to the original password to improve security, commonly known as "adding salt": passwd. update (bytes ('20140901', encoding = 'utf-8') print (passwd. hexdigest () # d2641b3d7243c87fe3f1312a30fe9909ae80d034f0a799da0897934311ee351b
5. datetime Module

Datetime is a time-related module that can process interchange between dates and times. The usage of datetime is as follows:

Import datetimeprint (datetime. datetime. now () #15:46:40. 784376 obtain the current date and time print (datetime. datetime. now () + datetime. timedelta (days = 10) #15:47:45. 702528 postpone the current time by 10 days print (datetime. date. today () #2016-05-17 get the current date print (datetime. datetime. utcnow () #08:23:41. 150628 obtain the Greenwich Mean Time print (datetime. datetime. now (). timetuple () # time. struct_time (tm_year = 2016... tm_hour = 16 ,...) obtain the current struct print (datetime. datetime. now (). timestamp () #1463473711.057878 obtain the current timestamp print (datetime. datetime. fromtimestamp (1463473711.057878) #16:28:31. 057878 convert the timestamp to date and time print (datetime. datetime. strptime ('2017-05-17 16:28:31 ',' % Y-% m-% d % H: % M: % s ')) #16:28:31 str converted to datetimeprint (datetime. datetime. now (). strftime ('% D, % m % d % H: % m') #05/23/16, 05 23 datetime converted to str

 

Vi. format

In the past, we used to format the string with a percent sign. Now we use a more awesome way to format the string format. Let's take a look at the general usage of format.

Print ("1 am {}, age {}". format ('jason ', 18) # Use {} as the placeholder print ("1 am {}, age {}". format (* ['jason ', 18]) # Use * to pass a list to print ("1 am {0}, age {1}, score {1 }". format ('jason ', 18) # apply print ("1 am {name}, age {age}" by using numbers such as 0 and 1 }". format (name = 'jason ', age = 18) # use key reference to pass the key-Value Pair print ("1 am {name}, age {age }". format (** {'name': 'jason ', 'age': 18}) # Use ** to pass a dictionary print ("1 am {0 [0]}, age {1 [1]} ". format ([1, 2, 3], [4, 5, 6]) #1 am 1, age 5 print ("I am {: s}, age {: d }". format (* ["jason", 18]) # You can specify the integer print ("I am {:. 2% }". format (0.2) # I am 20.00%
VII. Exercises

Write a user login registration interface. The user's password is encrypted in the file using hashlib. during login, the user's password must be consistent with the password in the file.

Def sha (password): # encryption function passwd = hashlib. sha256 (bytes ('wxtrkbc', encoding = 'utf-8') passwd. update (bytes (password, encoding = 'utf-8') return passwd. hexdigest () def register (user, passwd): # register the function and encrypt the password. Then, it is stored in the file with open ('db', 'A') as f: f. write (user + ':' + sha (passwd) def login (user, passwd): # log on to the function and check whether the logon password is correct with open ('db ', 'R', encoding = 'utf-8') as f: for line in f: info = line. strip (). split (':') if user = info [0] and sha (passwd) = info [1]: # encrypt the password and compare it with the one stored in the file, similarly, print ('login success ') return True else: print ('login error') return Falsedef main (): k = input ('1 registration, 2 login ') if int (k) = 1: user = input ('input Username:') passwd = input ('input password: ') register (user, passwd) elif int (k) = 2: user = input ('input Username: ') passwd = input ('input password:') login (user, passwd) else: return

  

             

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.