Common Python functions

Source: Internet
Author: User
Tags floor division timedelta
Basic custom C _ init _ (self [, arg1,]) constructor (with some optional parameters) C _ new _ (self [, arg1,]) constructor (with some optional parameters); basic customization type

C. init (self [, arg1,...]) constructor (with some optional parameters)

C. new (self [, arg1,...]) constructor (with some optional parameters); it is usually used to set a subclass of the unchanged data type.

C. del (self) deconstruct

C. str (self) printable character output; built-in str () and print statements

C. string output during repr (self) runtime; built-in repr () and ''operators

C. unicode (self) B Unicode string output; built-in unicode ()

C. call (self, * args) indicates the callable instance

C. nonzero (self) defines the False value for the object; built-in bool () (starting from version 2.2)

C. len (self) "length" (can be used for classes); built-in len ()

Special method description

Object (value) comparison c

C. Comparison of cmp (self, obj) objects; built-in cmp ()

C. lt (self, obj) and less than/less than or equal; <及<=操作符< p>

C. gt (self, obj) and greater than/or equal to; corresponding to> and> = operators

C. eq (self, obj) and equal to/not equal to; corresponding = ,! = And <> operators

Attribute

C. getattr (self, attr) to obtain attributes; built-in getattr (); called only when the attributes are not found

C. setattr (self, attr, val) set attributes

C. delattr (self, attr) delete attributes

C. getattribute (self, attr) get attributes; built-in getattr (); always called

C. get (self, attr) (descriptor) get attributes

C. set (self, attr, val) (descriptor) to set attributes

C. delete (self, attr) (descriptor) delete attributes

Custom class/simulation type

Value type: binary operator

C. * add (self, obj) plus; + operator

C. * sub (self, obj) subtraction;-operator

C. * mul (self, obj) multiplication; * operator

C. * p (self, obj) Division;/operator

C. * truep (self, obj) True division;/operator

C. * floorp (self, obj) Floor Division; // operator

C. * mod (self, obj) modulo/remainder; % operator

C. * pmod (self, obj) division and modulo; built-in pmod ()

C. * multiply the power of pow (self, obj [, mod]); built-in pow (); ** operator

C. * lshift (self, obj) left shift; < <操作符< p>

Special method description

Custom class/simulation type

Value type: binary operator

C. * rshift (self, obj) shifts right;> operator

C. * and (self, obj) bitwise and; & Operator

C. * or (self, obj) bitwise or; | operator

C. * xor (self, obj) bitwise and or; ^ operator

Value type: unary operator

C. neg (self) one dollar negative

C. pos (self) mona1 positive

C. abs (self) absolute value; built-in abs ()

C. invert (self) reverse by bit ;~ Operator

Value type: Numerical conversion

C. complex (self, com) to complex (plural); built-in complex ()

C.int (self) to int; built-in int ()

C. convert long (self) to long; build-in long ()

C. convert float (self) to float; built-in float ()

Value type: basic notation (String)

C. oct (self) octal representation; built-in oct ()

C. hex (self) hexadecimal representation; built-in hex ()

Numeric Type: Numerical compression

C. coerce (self, num) is compressed to the same numerical type; built-in coerce ()

C. index (self) g when necessary, the optional numeric type of compression is integer (for example: used for slicing

Index, etc.

Sequence Type

Number of items in the C. len (self) sequence

C. getitem (self, ind) to obtain a single sequence element

C. setitem (self, ind, val) sets a single sequence element

C. delitem (self, ind) deletes a single sequence element

Special method description

Sequence Type

C. getslice (self, ind1, ind2) to obtain the sequence segment

C. setslice (self, i1, i2, val) sets the sequence segment

C. delslice (self, ind1, ind2) deletes a sequence segment

C. contains (self, val) f test sequence member; built-in in keyword

C. * add (self, obj) concatenation; + operator

C. * mul (self, obj) repetition; * operator

C. iter (self) create iteration class; built-in iter ()

Ing type

Number of items in C. len (self) mapping

C. hash (self) hash function value

C. getitem (self, key) obtains the value of the given key.

C. setitem (self, key, val) sets the value of the given key.

C. delitem (self, key) deletes the value of a given key.

C. missing (self, key) provides a default value if the specified key does not exist in the dictionary.

Remember several common python functions to avoid forgetting

Get the file extension function: return the file name path before the extension and extension.

OS .path.splitext('xinjingbao1s.jpg ')

('Xinjingbao1s ', '.jpg ')

OS and OS. path modules

OS. listdir (dirname): list directories and files under dirname

OS. getcwd (): get the current working directory

OS. curdir: returned but the former Directory ('.')

OS. chdir (dirname): change the working directory to dirname

OS. path. isdir (name): determines whether the name is a directory. if the name is not a directory, false is returned.

OS. path. isfile (name): determines whether the name is a file. if the name does not exist, false is returned.

OS. path. exists (name): determines whether a file or directory name exists.

OS. path. getsize (name): get the file size. if the name is a directory, return 0L

OS. path. abspath (name): obtain the absolute path.

OS. path. normpath (path): Standard path string format

OS. path. split (name): split the file name and Directory (in fact, if you fully use the directory, it will also separate the last directory as the file name, and it will not determine whether the file or directory exists)

OS. path. splitext (): separates file names and extensions

OS. path. join (path, name): connection directory and file name or directory

OS. path. basename (path): returns the file name.

OS. path. dirname (path): return file path

1. rename: OS. rename (old, new)

2. delete: OS. remove (file)

3. list the files in the directory: OS. listdir (path)

4. get the current working directory: OS. getcwd ()

5. change the working directory: OS. chdir (newdir)

6. create a multilevel Directory: OS. makedirs (r "c: \ python \ test ")

7. create a single directory: OS. mkdir ("test ")

8. delete multiple directories: OS. removedirs (r "c: \ python") # Delete all empty directories in the last Directory of the given path.

9. delete a single directory: OS. rmdir ("test ")

10. Get file attributes: OS. stat (file)

11. modify the file permission and timestamp: OS. chmod (file)

12. execute the operating system command: OS. system ("dir ")

13. start a new process: OS .exe c (), OS .exe cvp ()

14. execute the program in the background: osspawnv ()

15. terminate the current process: OS. exit (), OS. _ exit ()

16. separated File name: OS. path. split (r "c: \ python \ hello. py") --> ("c: \ python", "hello. py ")

17. separation extension: OS. path. splitext (r "c: \ python \ hello. py ") --> (" c: \ python \ hello ",". py ")

18. obtain the path name: OS. path. dirname (r "c: \ python \ hello. py") --> "c: \ python"

19. get the file name: OS. path. basename (r "r: \ python \ hello. py") --> "hello. py"

20. determine whether the file exists: OS. path. exists (r "c: \ python \ hello. py") --> True

21. determine whether the path is absolute: OS. path. isabs (r ". \ python \") --> False

22. check whether the directory is OS. path. isdir (r "c: \ python") --> True

23. determine whether the file is: OS. path. isfile (r "c: \ python \ hello. py") --> True

24. determine whether the file is a linked File: OS. path. islink (r "c: \ python \ hello. py") --> False

25. Get file size: OS. path. getsize (filename)

26. *******: OS. ismount ("c: \") --> True

27. search all files in the directory: OS. path. walk ()

[2. shutil]

1. copy a single file: shultil. copy (oldfile, newfle)

2. copy the entire directory tree: shultil. copytree (r ". \ setup", r ". \ backup ")

3. delete the entire directory tree: shultil. rmtree (r ". \ backup ")

[3. tempfile]

1. create a unique temporary file: tempfile. mktemp () --> filename

2. open the temporary file: tempfile. TemporaryFile ()

[4. StringIO] # cStringIO is a fast implementation module of the StringIO module.

1. create a memory file and write the initial data: f = StringIO. StringIO ("Hello world! ")

2. read memory file data: print f. read () # or print f. getvalue () --> Hello world!

3. write data to memory files: f. write ("Good day! ")

4. close the memory File: f. close ()

View source code print help 1 from time import *

2

3 def secs2str (secs ):

4 return strftime ("% Y-% m-% d % H: % M: % S", localtime (secs) 5

5

6 >>> secs2str (1227628280.0)

2008-11-25 23:51:20'

Returns the specified struct_time (current time by default) according to the specified formatted string.

Time and date formatting symbols in python:

% Y two-digit year (00-99)

% Y indicates the four-digit year (000-9999)

% M month (01-12)

One day in % d Month (0-31)

% H Hour in 24-hour format (0-23)

% I 12-hour (01-12)

% M minutes (00 = 59)

% S seconds (00-59)

% A local simplified week name

% A Local full week name

% B local simplified month name

% B local full month name

% C local date and time

% J one day in the year (001-366)

% P local equivalent of A. M. or P. M.

% U number of weeks in a year (00-53) Sunday is the start of the week

% W week (0-6), Sunday is the beginning of the week

% W number of weeks in a year (00-53) Monday is the start of the week

% X local date representation

% X local time representation

% Z current time zone name

% Itself

9. strptime (...)

Strptime (string, format)-> struct_time

Converts a time string to a time string in the array format based on the specified formatting character.

For example:

The format string for 11:45:39 is: % Y-% m-% d % H: % M: % S

Sat Mar 28 22:24:24 2009 formatted string: % a % B % d % H: % M: % S % Y

10. time (...)

Time ()-> floating point number

Returns the timestamp of the current time.

III. doubts

1. renewal

In struct_time, it seems useless to parse, for example

A = (2009, 6, 28, 23, 8, 34, 5, 87, 1)

B = (2009, 6, 28, 23, 8, 34, 5, 87, 0)

A and B indicate the time stamp and the standard time respectively. the conversion between them is related to the timestamp 3600, but the output is 646585714.0 after the conversion.

4. small applications

1. obtain the current time using python

Time. time () get the current timestamp

Time. localtime () struct_time form of the current time

Time. ctime () string format of the current time

2. format strings in python

Formatted as 11:45:39

Time. strftime ("% Y-% m-% d % H: % M: % S", time. localtime () is formatted as Sat Mar 28 22:24:24 2009

Time. strftime ("% a % B % d % H: % M: % S % Y", time. localtime () 3. convert the format string to a timestamp

A = "Sat Mar 28 22:24:24 2009"

B = time. mktime (time. strptime (a, "% a % B % d % H: % M: % S % Y "))

Python time datetime module details

Time module:

--------------------------

Time () # returns the number of seconds since the Linux New Century in floating point format. In linux, 00:00:00 UTC,

January 1, 1970 is the beginning of the New ** 49.

>>> Time. time ()

1150269086.6630149

>>> Time. ctime (1150269086.6630149)

>>> 'Wed Jun 14 15:11:26 123'

Time. ctime ([sec]) # converts the number of seconds to the date format. If no parameter is included, the current time is displayed.

>>> Import time

>>> Time. ctime ()

>>> 'Wed Jun 14 15:02:50 123'

>>> Time. ctime (1138068452427683)

'Sat Dec 14 04:51:44 123'

>>> Time. ctime (OS. path. getmtime ('E: \ untitleds.bmp '))

'Fri Sep 19 16:35:37 123'

>>> Time. gmtime (OS. path. getmtime ('E: \ untitleds.bmp '))

Time. struct_time (maid = 2008, tm_mon = 9, tm_mday = 19, tm_hour = 8, tm_min = 35,

Tm_sec = 37, tm_wday = 4, tm_yday = 263, tm_isdst = 0)

Convert the modification time of a file to the date format (second to date)

>>> Time. strftime ('% Y-% m-% d % X', time. localtime (OS. path. getmtime ('E: \ untitleds.bmp ')))

'2017-09-19 16:35:37'

# Timed for 3 seconds.

>>> Time. sleep (3)

TIME module reference:

---------------------------------

# Retrieve the modification time of an object

>>> OS. path. getmtime ('E: \ untitleds.bmp ')

1221813337.7626641

Variable

The difference between the timezone Universal coordination time and the local standard time, in seconds.

Difference between the altzone universal coordination time and local compaction time

Daylight indicates whether the local time reflects the daylight saving time.

Tzname (standard time zone name, time zone name in milliseconds)

Function

Time () returns the number of seconds since the epoch.

Clock () returns the time when the CPU starts the process with a floating point number (or the time when the function is called the first time)

Sleep () delays the number of seconds represented by floating points.

Gmtime () converts the time expressed in seconds to a Universal Coordinated Time sequence.

Localtime () converts seconds to local time series

Asctime () converts a time series into a text description

Ctime () converts a second to a text description

Mktime () converts a local time sequence to a second

Strftime () converts a sequence to a text description in a specified format

Strptime () parses time series from text descriptions in a specified format

Tzset () changes the local time zone value

DateTime module

----------------------------

Datetime converts a date to a second.

-------------------------------------

>>> Import datetime, time

>>> Time. mktime (datetime. datetime (2009, 1, 1). timetuple ())

1230739200.0

>>> Cc = [, 11,] # Attributes: year, month, day, hour, minute,

Second

>>> Time. mktime (datetime. datetime (cc [0], cc [1], cc [2], cc [3], cc [4], cc [5]). timetuple ())

973226613.0

Convert seconds to date format

>>> Cc = time. localtime (OS. path. getmtime ('E: \ untitleds.bmp '))

>>> Print cc [0: 3]

(2008, 9, 19)

DateTime example

-----------------

Computing the number of days for calculating the difference between two dates

>>> Import datetime

>>> D1 = datetime. datetime (2005, 2, 16)

>>> D2 = datetime. datetime (2004, 12, 31)

>>> (D1-d2). days

47

Demo of computing run time, displayed in seconds

Import datetime

Starttime = datetime. datetime. now ()

# Long running

Endtime = datetime. datetime. now ()

Print (endtime-starttime). seconds

This example calculates the time from the current time to the next 10 hours.

>>> D1 = datetime. datetime. now ()

>>> D3 = d1 + datetime. timedelta (hours = 10)

>>> D3.ctime ()

Common classes include datetime and timedelta. They can be added or subtracted from each other. Each class has some methods and attributes to view specific values.

The above describes how to use common functions in Python. For more information, see other related articles in the first PHP community!

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.