Originally from the blog Park and CSDN
1. Calculation function
ABS ()--Take absolute value
Max ()--take the maximum of the sequence, including list, tuple
Min ()--Take the minimum value of the sequence
Len ()--Take length
Divmod (A, B)---take a//b divisor integers and the remainder to become a tuple
Pow (x, y)--Take the Y power of X
Pow (x, y, z) is the power of X.
Round ()--Modify the accuracy, if not, default to 0 bits
Range () to quickly generate a list
2. Other functions
Callable ()--Returns whether callable returns True or False
Isinstance (A,type)---Determine whether the preceding is the type that follows, returns TRUE or False
CMP (A, B)---Determine if AB is equal, return 0,a<b return -1,a>b return 1
Range ()--quickly generate a list of types
Xrange ()---quickly generate a list of type xrange
3. type conversion function
Type ()
Int ()
Long ()
Float ()
Complex ()--Convert to negative
Hex ()--Convert to Hex
Oct ()--Convert to octal
Chr ()--parameter 0-252, returns the current ASCII code
Ord ()--The ASCII code of the parameter, returning the corresponding decimal integer
4.string function
Str.capitalize ()--capitalize the first letter of the string
Str.replace (A.B)---change string A to B
Str.split ()---Split the string, the first parameter is the delimiter, and the subsequent argument is split several times.
String function Import uses
5. Sequence functions
Filter ()--filters return to true return sequence
lambda--defining functions
The ZIP ()---compresses multiple lists into a new list, but if the number of elements in multiple lists is different, the combined results are grouped by the fewest elements
map--multiple lists to be compressed into a new list, but if the number of elements in multiple lists is different, the result is that all elements are taken out and the missing is replaced by none. If it is none, direct combination, if it is a function, can be combined by function
Reduce ()--the previous two execution functions for each element, followed by functions such as factorial, step plus, and subsequent elements
--------------------------------------------------------------------------------------------------------------- --------
--------------------------------------------------------------------------------------------------------------- --------
UrlEncode and UrlDecode
When the URL contains Chinese or the parameter contains Chinese, the Chinese or special characters (/, &) need to be encoded for conversion.
The essence of UrlEncode: Convert the string to GBK encoding, and then replace the \x with%. If the terminal is UTF8 encoded, you need to turn the result into a UTF8 output, otherwise it will be garbled.
UrlEncode
The UrlEncode function inside the Urllib library can urlencode and convert the key and value of the Key-value health value to the a=1&b=2 string.
#key-value健值对>>> from urllib import urlencode>>> data={‘a‘:‘a1‘,‘b‘:‘中文‘}>>> print urlencode(data)a=a1&b=%E4%B8%AD%E6%96%87>>> data={‘a‘:‘a1‘,‘b测试‘:‘中文‘}>>> print urlencode(data)a=a1&b%E6%B5%8B%E8%AF%95=%E4%B8%AD%E6%96%87
The quote function inside the Urllib library can be UrlEncode converted to a single string.
#string>>> from urllib import quote>>> data="测试">>> print quote(data)%E6%B5%8B%E8%AF%95
UrlDecode
Urllib only provides the unquote () function.
>>> from urllib import unquote>>> unquote("%E6%B5%8B%E8%AF%95")‘\xe6\xb5\x8b\xe8\xaf\x95‘>>> print unquote("%E6%B5%8B%E8%AF%95")测试>>>
JSON processing
Two functions:
function |
Description |
Json.dumps |
Encode a Python object as a JSON string (Object---string) |
Json.loads |
Decodes an encoded JSON string into a Python object (string--object) |
Json.dumps
Syntax: Json.dumps (data, Sort_keys=true, indent=4,separators= (Self.item_separator, Self.key_separator))
>>> Import JSON>>> data={A:"A1", "B" : "B1"} >>> jsonstr=json.dumps (data) >>> print jsonstr{< Span class= "hljs-string" > "a" : "A1", "B" : "B1"} #输出格式化 >>> print json.dumps (data, Sort_keys=true, Indent=4,separators= ( "," "a" : "A1", "B" : "B1"} >>>
The conversion table of the Python primitive type to JSON type:
Python |
JSON |
Dict |
Object |
List,tuple |
Array |
Str,unicode |
String |
Int,long,float |
Number |
True |
True |
False |
False |
None |
Null |
Json.loads
json.loads--returns the data type of the Python field
>>>Import JSON>>> jsonstr=' {' A ': ' A1 ', ' B ': ' B1 '} '>>>Print Json.loads (JSONSTR) {U ' A ':U ' A1 ',U ' B ':U ' B1 '}>>> jsonstr=' {' A ': ' A1 ', ' B ': null, ' C ': false, ' d ': {' AA ': ' Aa1 ', ' BB ': ' BB1 '} '>>> Print json.loads (jsonstr) {u ' a ': u ' A1 ', U ' C ': False, u ' B ': None, u ' d ': {u ' AA ': u ' aa1 ', u ' bb ': u ' bb1 '}}>>> jsonstr=' [{"A": "A1"},{"B": "B2"}] ' >>> Print json.loads (jsonstr) [{u ' a ': u ' A1 '}, {u ' B ': u ' B2 '}]
JSON type conversion to Python type comparison table
JSON |
Python |
Object |
Dict |
Array |
List |
String |
Unicode |
Number (int) |
Int,long |
Number (real) |
Float |
True |
True |
False |
False |
Null |
None |
Conclusion: Print only outputs Python-recognized data types, and python.dumps can format the output.
Computes the string MD5
Method One: Use the MD5 package
Import MD5 def calMd5 (signdata,signkey,joiner=""): signdata=signdata+joiner+""+ Signkey m=md5.new (signdata) = m.hexdigest () return sign
Method Two: Use the Hashlib package
Import Hashlib def calHashMd5 (signdata,signkey,joiner=""): signdata=signdata+joiner+"" +Signkey m=hashlib.md5 (signdata) = m.hexdigest () return Sign
Calculate HMACSHA1
HMAC: Key-related hash operation message authentication code, the HMAC operation takes advantage of a hashing algorithm (either MD5 or SHA-1), with a key and a message as input, generating a message digest as output.
Role:
(1) Verifying the accepted authorization data and authentication data;
(2) Confirm that the received command request is an authorized request and that the transfer process has not been tampered with
Import HMAC Import Base64 def hmacsha1withbase64 (signdata,signkey): = hmac.new (Signkey, SIGNDATA,SHA1). Digest () = base64.b64encode (sign) return Sign
string concatenation
fromCollectionsImportordereddictdefComposestr (data,joiner,withkey=true,key_value_joiner="="): Data= Ordereddict (sorted (Data.items (), key=Lambdat:t[0])) ifWithkey:signdata= Joiner.join ([Key_value_joiner.join (str (key), str (elem)) forKey, EleminchData.iteritems ()]) Else: SignData= Joiner.join ([elem forKey, EleminchData.items ()]) returnSignData
Python common functions and modules