The usage of various functions in python, python basic functions pdf

This article will talk about float(input()), a complete collection of python basic functions, and the usage of various functions in python. I hope it will be helpful to you. Don’t forget to bookmark this site.

1. What are the commonly used function packages in python?

Some python commonly used function packages:

1、Urllib3

Urllib3 is a Python HTTP client that has many features missing from the Python standard library:

  • thread safety

  • connection pool

  • Client SSL/TLS Verification

  • Upload files using multipart encoding

  • Helpers for retrying requests and handling HTTP redirects

  • Support gzip and deflate encoding

  • Proxy support for HTTP and SOCKS

2、Six

six is ​​a Python 2 and 3 compatibility library. This project aims to support codebases that can run on both Python 2 and 3. It provides a number of functions that simplify the syntax differences between Python 2 and 3.

3、botocore、boto3、s3transfer、awscli

Botocore is the underlying interface of AWS. Botocore is the basis for the Boto3 library (#22), which lets you use services like Amazon S3 and Amazon EC2. Botocore is also the basis for AWS-CLI, which provides a unified command line interface for AWS.

S3transfer (#7) is a Python library for managing Amazon S3 transfers. It's under active development, and the intro page doesn't recommend that people use it now, or at least wait until the version is fixed, because the API is subject to change, both between minor versions. Boto3, AWS-CLI, and many other projects rely on s3transfer.

4、Pip

pip is a recursive acronym for "Pip Installs Packages".

pip is easy to use. To install a package just pip install <package name>, and to remove a package just pip uninstall <package name>.

One of the biggest advantages is that it can get a list of packages, usually as a file. This file can optionally contain a detailed specification of the desired version. Most Python projects contain such files.

If you combine pip with virtualenv (#57 in the list), you can create predictably isolated environments without interfering with the underlying system, or vice versa.

5、Python-dateutil

The python-dateutil module provides powerful extensions to the standard datetime module. My experience is that if regular Python datetime lacks functionality, python-dateutil can make up for it.

6、Requests

Requests is built on top of our #1 library - urllib3. It makes web requests very easy. Many people prefer this package over urllib3. And probably more end users use it than urllib3 too. The latter is more low-level, and given its level of control over internals, it's generally a dependency of other projects.

7. Certificate

In recent years, almost all websites have switched to SSL, which you can recognize by the little lock symbol in the address bar. A small lock means communication with the site is secure and encrypted, preventing eavesdropping.

8、Idna

According to its PyPI page, idna provides "support for the Internationalized Domain Names in Applications (IDNA) protocol as specified in RFC5891."

At the heart of IDNA are two functions: ToASCII and ToUnicode. ToASCII converts an international Unicode field to an ASCII string. ToUnicode reverses the process. In the IDNA package, these functions are called idna.encode() and idna.decode()

9、PyYAML

YAML is a data serialization format. It's designed so that the code can be easily read by both humans and computers -- humans can easily read and write its contents, and computers can parse it.

PyYAML is a YAML parser and emitter for Python, which means it can read and write YAML. It will write any Python object as YAML: lists, dictionaries, and even class instances are included.

10、Pyasn1

Like IDNA above, this project is also very useful:

Pure Python implementation of ASN.1 types and DER/BER/CER encodings (X.208)

Fortunately, this decades-old standard has a lot of information available. ASN.1 is the abbreviation of Abstract Syntax Notation One, it is like the godfather of data serialization. It comes from the telecommunications industry. Maybe you know Protocol Buffers or Apache Thrift? This is their 1984 version.

11、Docutils

Docutils is a modular system for processing plain text documents into many useful formats such as HTML, XML, and LaTeX. Docutils can read plain text documents in reStructuredText format, which is an easy-to-read markup syntax similar to MarkDown.

12、The Chard

You can use the chardet module to check the character set of a file or data stream. This can be useful, for example, when large amounts of random text need to be analyzed. But you can also use it when working with remotely downloaded data, but you don't know what character set is used.

13、RSA

The rsa package is a pure Python implementation of RSA. It supports:

  • encryption and decryption

  • Signing and verifying signatures

  • Generate keys according to PKCS#1 version 1.5

It can be used both as a Python library and from the command line.

14、Jmespath

JMESPath, pronounced "James path", makes working with JSON in Python easier. It allows you to declaratively specify how to extract elements from a JSON document.

15、Setuptools

It is a tool for creating Python packages. However, its documentation is terrible. It doesn't clearly describe what it's for, and the documentation contains dead links. The best source of information is this site, especially this guide to creating Python packages.

16、Pytz

Like dateutils, this library helps you work with dates and times. Sometimes time zones can be cumbersome to deal with. Thankfully there are packages like this that make things a little easier.

17、Futures

Starting with Python 3.2, python provides the current.futures module to help you achieve asynchronous execution. The futures package is a backport of this library for Python 2. It is not available for Python3 users, since Python 3 provides this module natively.

18、Colorama

With Colorama, you can add some colors to your terminal:

For more Python knowledge, please pay attention to Python Self-study Network

2. What are the common functions in Python basic numpy

Some Python novices don't know much about the common functions in numpy. Today, I will sort it out and share it with you .
Numpy is a scientific computing library for Python that provides matrix operations and is generally used with Scipy and matplotlib. In fact, list already provides a matrix-like representation, but numpy provides us with more functions.
Array common functions
1.where() returns the index value of the array according to the condition
2.take(a,index) takes the value from the array a according to the index index
3.linspace(a,b,N) returns a value in (a,b) An array evenly distributed within the range, the number of elements is N
() Fill all the elements of the array with the specified value
5.diff(a) returns the array formed by the difference between the adjacent elements of array a
6.sign(a) returns The positive and negative sign of each element of array a
7.piecewise(a,[condlist],[funclist]) array a returns the corresponding element result according to the Boolean condition condlist
8.a.argmax(), a.argmin() returns a The index of the largest and smallest element
Change the array dimension
a.ravel(), a.flatten(): flatten the array a into a one-dimensional array
a.shape=(m,n), a.reshape(m,n): reshape the array a is converted into an m*n-dimensional array
a.transpose, aT transposed array a
array combination
1.hstack((a,b)),concatenate((a,b),axis=1) array a,b along the horizontal direction combination
2.vstack((a,b)),concatenate((a,b),axis=0) combine the arrays a and b vertically
3.row_stack((a,b)) combine the arrays a and b by row Direction combination
4.column_stack((a,b)) combines the arrays a and b in the column direction
Array segmentation
1.split(a,n,axis=0),vsplit(a,n) divides the array a vertically into n arrays
2.split(a,n,axis=1), hsplit(a,n) splits the array a into n arrays in the horizontal direction. Array
pruning and compression
(m,n) sets the range of array a to (m , n), the elements greater than n in the array are set to n, and the elements less than m are set to m 2.a.compress() returns the array
filtered according to the given conditions. Type 2.a.shape Dimensions of array a Dimensions of array a Total number of elements contained in array a 5.a.itemsize Number of bytes occupied by elements of array a in memory 6.a.nbytes entire array a Occupied memory space 7.a.astype(int) converts the type of array a to int type Array calculation 1.average(a,weights=v) performs weighted average on array a with weight v 2.mean(a),max (a), min(a), middle(a), var(a), std(a) the mean, maximum, minimum, median, variance, standard deviation of array a () of all elements of array a product











4.a.cumprod() Cumulative product of the elements of array a
5.cov(a,b), corrcoef(a,b) Covariance and correlation coefficient of array a and b
6.a.diagonal() View matrix a pair Elements on the diagonal 7.a.trace() calculates the trace of the matrix a, that is, the sum of the elements on the diagonal
The above are common functions in numpy. More Python learning recommendations: PyThon Learning Network Teaching Center.

3. What are the commonly used system functions in python

1. Commonly used built-in functions: (can be used directly without import)
help(obj) online help, obj can be any type
callable(obj) Check whether an obj can call
repr(obj) like a function to get the representation string of obj, You can use this string eval to rebuild a copy of the object
eval_r(str) represents a legal python expression, return this expression
dir(obj) view the name visible in the name space of obj
hasattr(obj,name) view an obj's Whether there is a name in the name space
getattr(obj,name) Get a name in the name space of an obj
setattr(obj,name,value) For a name in the name space of an obj, point to the object vale
delattr(obj,name) Removes a name vars(obj) from obj's name space
Returns an object's name space. Use dictionary to represent
locals() Return a local name space, use dictionary to represent
globals() Return a global name space, use dictionary to represent
type(obj) Check the type of an obj
isinstance(obj,cls) Check whether obj is an instance
issubclass of cls (subcls,supcls) Check whether subcls is a subclass of supcls

The type conversion function
chr(i) turns an ASCII value into a character
ord(i) turns a character or unicode character into an ASCII value
oct(x) turns an integer x into an octal string
hex(x) turns an integer x becomes a string str(obj) represented in hexadecimal,
get the string description list(seq) of obj
convert a sequence into a list
tuple(seq) convert a sequence into a tuple
dict(), dict(list ) to a dictionary
int(x) to an integer
long(x) to a long integer
float(x) to a floating-point number
complex(x) to a complex number
max(...) to find the maximum value
min(. ..) Find the minimum value
. The built-in function complie used to execute the program
. If a piece of code is often used, it will be faster to compile it first and then run it.

2. Calls related to the operating system The
system-related information module import sys
is a list that contains all command line parameters.
sys.stdout sys.stdin sys.stderr respectively represent the file objects of standard input and output and error output.
sys.stdin .readline() reads a line from standard input sys.stdout.write("a") screen output a
(exit_code) Exit the program
sys.modules is a dictionary, which means that all available modules in the system
sys.platform is running in the operating system environment
is a list, indicating all the paths to find modules and packages.

Operating system related calls and operations import os
os.environ A dictionary containing the mapping relationship of environment variables os.environ["HOME"] can get the value of the environment variable HOME
os.chdir(dir) Change the current directory os.chdir('d:\\outlook') Pay attention to windows Use escape
os.getcwd() to get the current directory
os.getegid() to get the effective group id os.getgid() to get the group id
os.getuid() to get the user id os.geteuid() to get the effective user id
os.setegid os .setegid() os.seteuid() os.setuid()
os.getgruops() Get user group name list
os.getlogin() Get user login name
os.getenv Get environment variable
os.putenv Set environment variable
os.umask Set umask
os.system(cmd) Use the system call to run the cmd command
Operation example:
os.mkdir('/tmp/xx') os.system("echo 'hello' > ") os.listdir('/tmp/xx')
os.rename('','') os.remove('' ) os.rmdir('/tmp/xx')
write a simple shell in python
#!/usr/bin/python
import os, sys
cmd = sys.stdin.readline()
while cmd:
os.system(cmd)
cmd = sys.stdin.readline()

is used to write platform-independent programs
. abspath("1.txt") == (os.getcwd(), "1.txt")
.split(os.getcwd()) is used to separate The directory part and the file name part of a directory name.
(os.getcwd(), os.pardir, 'a', 'a.doc') Full path name.
os.pardir represents the character of the upper level directory under the current platform..
.getctime("") returns 1. txt's ctime (creation time) timestamp.exists
(os.getcwd()) determines whether the file exists.expanduser
('~/dir') expands ~ into the user root directory
.

.isdir('c:\Python26\temp') Determine whether it is a directory, 1 is 0 or
not
. Unavailable under
windows.samefile(os.getcwd(), '/home/huaying') to see if the two file names refer to the same file
('/home/huaying', test_fun, "ac")
traverse / All subdirectories under home/huaying include this directory, and the function test_fun will be called for each directory.
Example: In a certain directory, search for a file or directory named ac in all its subdirectories.
def test_fun(filename, dirname, names): //filename is the ac in walk dirname is the name of the directory to visit
if filename in names: //names is a list containing all the contents of the dirname directory
print (dirname, filename)
('/home/huaying', test_fun, "ac")

file operation
open file
f = open("filename", "r") r read-only w write rw read-write rb read binary wb write binary w+write append read-write
file
f. write("a") f.
f.read() reads all the characters f.read(size) reads size characters from the file
f.readline() reads a line until the end of the file and returns an empty string. f.readlines() reads all and returns a list. Each element of the list represents a line, including "\n"\
f.tell() returns the current file reading position
f.seek(off, where) locates the reading and writing position of the file. off indicates the offset, and the positive number points to the file Move to the tail, and a negative number means to move to the beginning.
where is 0 means counting from the beginning, 1 means counting from the current position, and 2 means counting from the end.
f.flush() refresh cache
close file
f.close()

regular expression regular expression import re
simple regexp
p = re. compile("abc") if p.match("abc") : print "match"
In the above example, a pattern (pattern) is first generated, and if it matches a certain string, a match object is returned
except some special characters metacharacter Metacharacters, most characters match themselves.
These special characters are. ^ $ * + ? { [ ] \ | ( )
The character set (expressed by [])
lists characters, such as [abc] means to match a or b or c, and most metacharacters in [] only mean to match themselves. Example:
a = ".^$*+?{\\|()" Most metachars match themselves in [], but "^[]\" is different
p = re.compile("["+a+"]")
for i in a:
if p.match(i):
print "[%s] is match" %i
else:
print "[%s] is not match " %i
contains [] itself in [], which means "[" or "]" match. It is represented by
and
.
^ appears at the beginning of [], which means negation. [^abc] means except a, b, c All characters except . ^ does not appear at the beginning, that is, it matches the body.
- It can represent the range. [a-zA-Z] matches any English letter. [0-9] matches any digit.
The magical use of \ in [].
\d [0-9]
\D [^0-9]
\s [ \t\n\r\f\v]
\S [^ \t\n\r\f\v]
\w [a-zA -Z0-9_]
\W [^a-zA-Z0-9_]
\t means match with tab, others are consistent with string notation
\x20 means match with hexadecimal ascii 0x20
With \, you can In [] means any character. Note: If a single "." does not appear in [], it means that any character other than newline \n is matched, similar to [^\n]. The repetition {m, n} of regexp means that there are more than m (including
m
) ), less than n (including n). For example, ab{1,3}c matches abc, abbc, abbbc, and will not match ac,
m is the lower bound and n is the upper bound. The lower bound of the m omitted table is 0, the n omitted, and the upper bound of the table is infinite.
* means {,} + means {1,} ? means {0,1}
maximum match and minimum match python is the maximum match, if you want the minimum match, add a ? after *,+,?,{m,n} The end of the .match
object can get the position of the last character matched.
re.compile("a*").match('aaaa').end() 4 maximum match
re.compile("a*?").match('aaaa').end() 0 minimum match
using original characters String
\\ is used in the string representation method to represent the character \. Extensive use affects readability.
Solution: Add an r in front of the string to indicate the raw format.
a = r"\a" print a The result is \a a
= r"\"a" print a The result is \"a
Use the re module to
first use re.compile to get a RegexObject to represent a regexp
and then use pattern match and search Method, get MatchObject
and then use match object to get matching position, matching string and other information
RegxObject common function:
>>> re.compile("a").match("abab") If the beginning of abab and re.compile( "a"

>>> print re.compile("a").match("bbab")
None Note: start matching from the beginning of str
>>> re.compile("a").search("abab") Search in abab The first part that matches re_obj
<_sre.SRE_Match object at 0x81d43c8>
>>> print re.compile("a").search("bbab")
<_sre.SRE_Match object at 0x8184e18> is different from match(), it does not have to Match from the beginning
re_obj.findall(str) Return str to search for all parts that match re_obj.
Return a tuple, where the elements are matched strings. The common function m.start()
of MatchObject returns the starting position, m.end(
) returns the end position (not including the character at the position).
m.span() returns a tuple representation (m.start(), m.end())
m.pos(), m.endpos(), m.re (), m.string()
m.re().search(m.string(), m.pos(), m.endpos()) will get m itself
m.finditer() can return an iterator for Traverse all found MatchObjects.
for m in re.compile("[ab]").finditer("tatbxaxb"):
print m.span()
advanced regexp
| Indicates the combination of multiple regexps. AB two regexps, A|B means match with A or match with B.
^ means only match the beginning of a line, and ^ has this special meaning only at the beginning.
$ means only match the end of a line
\A means only match the beginning of the first line of strings ^ match the beginning of each line
\Z means only match the end of a line of strings $ match the end of the first line
\b only match words Boundary example: \binfo\b will only match "info" but not information
\B means match a non-word boundary
Example as follows:
>>> print re.compile(r"\binfo\b").match("info " ) #Use raw format \b to indicate word boundary
<_sre.SRE_Match object at 0x817aa98>
>>> print re.compile("\binfo\b").match("info ") #No use raw \b to indicate backspace symbol
None
>>> print re.compile("\binfo\b").match("\binfo\b ")
<_sre.SRE_Match object at 0x8174948>
Group (Group) Example: re.compile("(a(b) c)d").match("abcd").groups() ('abc', 'b'




Address: BUPT

name: Ann
Address: BUPT
"""
#p = re.compile(r"^name:(.*)\n^Address:(.*)\n", re.M)
p = re.compile (r"^name:(?P.*)\n^Address:(?P.*)\n", re.M)
for m in p.finditer(x):
print m.span()
print "here is your friends list"
print "%s, %s"%m.groups()
Compile Flag
When using re.compile to get RegxObject, you can have some flags to adjust the detailed characteristics of RegxObject.
DOTALL, S Let . Match any character, Include line break \n
IGNORECASE, I ignore case
LOCALES, L make \w \W \b \B consistent with current locale
MULTILINE, M multiline mode, only affects ^ and $ (see above example)
VERBOSE, X verbose mode

4. What are the built-in functions of python and what do they mean?

print-output, input-input, int-convert strings to numbers (strings must be numbers), str-convert numbers to strings, list-convert strings/numbers to lists, for-limited loops, while- Infinite loop……………………………………

Guess you like

Origin blog.csdn.net/chatgpt001/article/details/129142795