1. Python and Python features
1. Python is a programming language, one of many.
2, syntax concise, elegant, written programs easy to read;
3. Cross-platform, running on Windows, Linux and MacOS;
4. Easy to learn. From the perspective of non-computer majors, python is easier to learn and master than C++, Java, JavaScript and other languages if programming is used as a problem-solving tool.
5. Extremely powerful standard libraries and third-party libraries, such as email, such as graphical GUI interfaces;
Python is an object-oriented language. (Object orientation is an idea.)
Why do I like Python?
1, simple, flexible, elegant, philosophical; (Zen of Python)
Easy to use is difficult to master;
3. Python has both dynamic scripting and object-oriented features.
4. Application: crawler, big data, testing, Web, AI, script processing
The disadvantage of python
Compiled languages (C++), interpreted languages (JavaScript, Python), Java and C# are intermediate languages (their classification is not important). The world is not only the Web, there are many problems need to use programming to solve. Don’t limit your thinking to the Web, it’s just an application of programming
What Python can do,
1, the crawler
2. Big Data and Data Analytics (Spark)
3. Automated operation and maintenance and automated testing
4. Web development: Flask, Django
Tensor Flow
6. Glue language: mix other languages such as C++, Java, etc. The ability to easily combine modules from other languages (especially C/C++) how to use Python: When you have a problem, pick up Python and write a tool. Is this the right way to open Python
Python3 basic syntax
1. The encoding
By default, Python 3 source files are encoded in UTF-8 and all strings are Unicode strings. Of course, you can also specify a different encoding for the source file:
# -*- coding: cp-1252 -*-Copy the code
The above definition allows the use of character encodings from the Windows-1252 character set in source files. The appropriate languages are Bulgarian, Beloese, Macedonian, Russian, and Serbian.
2. The identifier
- The first character must be an alphabetic letter or underscore _.
- The rest of the identifier consists of letters, numbers, and underscores.
- Identifiers are case-sensitive.
In Python 3, Chinese variable names are allowed, and non-ASCII identifiers are allowed.
3. The python reserved words
Reserved words are keywords, and we cannot use them as any identifier names. Python’s standard library provides a keyword module that prints all the keywords in the current version:
>>> import keyword
>>> keyword.kwlist
['False'.'None'.'True'.'and'.'as'.'assert'.'break'.'class'.'continue'.'def'.'del'.'elif'.'else'.'except'.'finally'.'for'.'from'.'global'.'if'.'import'.'in'.'is'.'lambda'.'nonlocal'.'not'.'or'.'pass'.'raise'.'return'.'try'.'while'.'with'.'yield']Copy the code
4. Comment
In Python, single-line comments start with #, as shown in the following example:
Instance (Python 3.0 +)
# first comment
print ("Hello, Python!") # second commentCopy the code
Execute the above code and the output is:
Hello, Python!Copy the code
Multi-line comments can use multiple # signs, as well as ” and “” :
Instance (Python 3.0 +)
# first comment
# second comment
' ''Note 3, note 4'' '
"""Note 5, note 6."""
print ("Hello, Python!")Copy the code
Execute the above code and the output is:
Hello, Python!Copy the code
5. Line and indent
Python’s most distinctive feature is the use of indentation to represent blocks of code without the use of curly braces {}.
The number of indent Spaces is variable, but statements in the same code block must contain the same number of indent Spaces. Examples are as follows:
Instance (Python 3.0 +)
if True:
print ("True")
else:
print ("False")Copy the code
The last line of the following code does not indent the same number of Spaces, resulting in a runtime error:
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False") Indenting is inconsistent, causing a runtime errorCopy the code
The following error may occur after execution:
File "test.py", line 6
print ("False") Indenting is inconsistent, causing a runtime error
^
IndentationError: unindent does not match any outer indentation levelCopy the code
6. Multi-line statements
Python usually writes a single statement on one line, but if the statement is long, we can use a backslash (\) to implement multi-line statements, for example:
total = item_one + \
item_two + \
item_threeCopy the code
Multi-line statements in [], {}, or () do not require a backslash (\), for example:
total = ['item_one'.'item_two'.'item_three'.'item_four'.'item_five']Copy the code
7. Number type
There are four types of numbers in Python: integers, Booleans, floats, and complex numbers.
- Int (integer), such as 1, has only one integer type int, which is represented as a Long integer. There is no Long in Python2.
- Bool (Boolean), as True.
- Float (float), e.g. 1.23, 3e-2
- Complex, e.g.1 + 2j, 1.1 + 2.2j
8. String (String)
- Single and double quotation marks are used exactly the same in Python.
- Use triple quotes (“” or “””) to specify a multi-line string.
- Escape character ‘\’
- Backslashes can be used to escape, and r prevents backslashes from escaping. If r”this is a line with \n”, \n will display, not a newline.
- Cascading strings such as “this “, “is “, and “string” are automatically converted to “this is string”.
- Strings can be concatenated with the + operator and repeated with the * operator.
- Strings in Python are indexed in two ways, starting with 0 from left to right and -1 from right to left.
- Strings in Python cannot be changed.
- Python has no separate character types; a character is a string of length 1.
- The syntax for intercepting a string is as follows: variable [header subscript: tail subscript: step]
word = 'String'
sentence = "It's a sentence."
paragraph = """This is a paragraph. It can be multiple lines."""Copy the code
Instance (Python 3.0 +)
str='Runoob'
print(str) # output string
print(str[0:-1]) Print all characters from the first to the penultimate
print(str[0]) # Print the first character of the string
print(str[2:5]) # print characters from the third to the fifth
print(str[2:]) # print all characters from the third
print(str * 2) Print the string twice
print(str + 'hello') # connect string
print('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --')
print('hello\nrunoob') # Use backslash (\)+n to escape special characters
print(r'hello\nrunoob') # Add an r to the front of the string to indicate the original string. No escape occursCopy the code
Here r stands for raw, raw string.
The output is:
Runoob Runoo R noo noob RunoobRunoob Runoob hello -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- hello Runoob hello \ nrunoobCopy the code
9. A blank line
A blank line separating functions or methods of a class indicates the beginning of a new code. The class and function entry are also separated by a blank line to highlight the beginning of the function entry.
Unlike code indentation, blank lines are not part of Python syntax. Write without inserting blank lines, and the Python interpreter runs without error. However, blank lines are used to separate two pieces of code with different functions or meanings for future maintenance or refactoring.
Remember: blank lines are part of the program code.
10. Wait for user input
Execute the following program to wait for user input after pressing enter:
Instance (Python 3.0 +)
input("\n\n press Enter and exit.")Copy the code
In the above code, “\n\n” prints two new blank lines before output. Once the user presses enter, the program exits.
11. Multiple statements are displayed in the same line
Python can use multiple statements on the same line, with semicolons (;) between them. Here is a simple example of splitting:
Instance (Python 3.0 +)
import sys; x = 'runoob'; sys.stdout.write(x + '\n')Copy the code
Execute the above code with the script, and the output is:
runoobCopy the code
Using the interactive command line, the output is:
>>> import sys; x = 'runoob'; sys.stdout.write(x + '\n')
runoob
7Copy the code
7 represents the number of characters.
12. Multiple statements form code groups
The indenting of the same set of statements forms a code block, called a code group.
Compound statements such as if, while, def, and class begin with a keyword and end with a colon (:), followed by one or more lines of code that form a code group.
We call the first line and the following group of code a clause.
Examples are as follows:
if expression :
suite
elif expression :
suite
else :
suiteCopy the code
13. Print output
Print defaults to newline output. If you want to implement non-newline output, end=”” :
Instance (Python 3.0 +)
x="a"
y="b"
# newline output
print( x )
print( y )
print('-- -- -- -- -- -- -- -- --')
No newline output
print( x, end="" )
print( y, end="" )
print(a)Copy the code
The execution results of the above examples are as follows:
a
b
---------
a bCopy the code
14. The import with the from… import
Use import or from in Python. Import to import the corresponding module.
Import the entire module (somemodule) in the format: import somemodule
Import a function from a module in the format: from somemodule import someFunction
Import multiple functions from a module in the format: From somemodule import FirstFunc, secondFunc, thirdFunc
Import all functions in a module in the format from somemodule import *
Import the SYS module
import sys
print('================Python import mode==========================')
print ('Command line arguments are :')
for i in sys.argv:
print (i)
print ('\n Python path is',sys.path)Copy the code
16. Import sys argv,path members
from sys import argv,path Import a specific member
print('================python from import===================================')
print('path:',path) # sys.path is not required for this reference because the path member has been importedCopy the code
17. Command line parameters
Many programs can perform operations to view basic information. Python can use the -h argument to view help information about each argument:
$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]Copy the code
Python3 basic data type
Variables in Python do not need to be declared. Each variable must be assigned a value before it can be used, and then the variable can be created.
In Python, a variable is a variable, it has no type, and by type we mean the type of the in-memory object to which the variable refers.
The equal sign (=) is used to assign values to variables.
The left side of the equal (=) operator is a variable name, and the right side of the equal (=) operator is the value stored in the variable. Such as:
Instance (Python 3.0 +)
counter = 100 Integer variablesMiles = 1000.0Float variables
name = "runoob" # string
print (counter)
print (miles)
print (name)Copy the code
Executing the above program produces the following results:
100
1000.0
runoobCopy the code
1. Assign multiple variables
Python allows you to assign values to multiple variables at the same time. Such as:
a = b = c = 1Copy the code
In the example above, create an integer object with the value 1 and assign it from back to front. All three variables are assigned the same value.
You can also specify multiple variables for multiple objects. Such as:
a, b, c = 1, 2, "runoob"Copy the code
In the above example, two integer objects 1 and 2 are assigned to variables A and B, and the string object “runoob” is assigned to variable C.
2. Standard data types
There are six standard data types in Python3:
- Number = Number
- String (String)
- List (List)
- Tuple (Tuple)
- Set
- The Dictionary
Of the six standard data types for Python3:
- Immutable data (3) : Number (Number), String (String), Tuple (Tuple)
- Mutable data: List, Dictionary, Set
3. What’s the Number?
Python3 supports int, float, bool, and complex.
In Python 3, there is only one integer type, int, which is represented as a Long integer. There is no Long in Python 2.
As with most languages, assignment and evaluation of numeric types are straightforward.
The built-in type() function can be used to query the type of object to which the variable refers.
>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>Copy the code
In addition, we can use isinstance to determine:
The instance
>>>a = 111
>>> isinstance(a, int)
True
>>>Copy the code
Isinstance differs from type in that:
type()
A subclass is not considered a superclass type.isinstance()
A subclass is considered a superclass type.
>>> class A:
... pass
...
>>> class B(A):
... pass
...
>>> isinstance(A(), A)
True
>>> type(A()) == A
True
>>> isinstance(B(), A)
True
>>> type(B()) == A
FalseCopy the code
Note: there is no Boolean in Python2, which uses the number 0 for False and 1 for True. In Python3, True and False are defined as keywords, but their values are still 1 and 0, and they can be added to numbers.
When you specify a value, the Number object is created:
var1 = 1
var2 = 10Copy the code
You can also use the DEL statement to remove some object references.
The syntax for a del statement is:
del var1[,var2[,var3[....,varN]]]Copy the code
You can delete single or multiple objects by using the DEL statement. Such as:
del var
del var_a, var_bCopy the code
4. Numerical calculation
The instance
> > > 5 + 4# addition9 >>> 4.3-2# subtraction
2.3
>>> 3 * 7 # multiplication21 >>> 2/4Divide to get a floating point number
0.5
>>> 2 // 4 Divide, get an integer0 >>> 17%3# take over
2
>>> 2 ** 5 # power
32Copy the code
Note:
- 1. Python can assign values to multiple variables at the same time, such as a, b = 1, 2.
- 2. A variable can be assigned to different types of objects.
- 3. Numeric division consists of two operators: / returns a floating point number, and // returns an integer.
- 4. In mixed calculations, Python converts integers to floating point numbers.
5. Numeric type instances
int | float | complex |
---|---|---|
10 | 0.0 | 3.14 j. |
100 | 15.20 | 45.j |
– 786. | 21.9 | 9.322 e-36 j |
080 | 32.3 e+18 | .876j |
– 0490. | – 90. | -.6545+0J |
-0x260 | 32.54 e100 | 3e+26J |
0x69 | 70.2 e-12 | 4.53 e-7 j |
Python also supports complex numbers, which consist of the real and imaginary parts and can be represented by a + bj, or complex(a,b), whose real a and imaginary b are both floating-point
6.String
Strings in Python are enclosed in single ‘or double’ quotes, and special characters are escaped using backslashes \.
The syntax for intercepting a string is as follows:
Variable [header subscript: tail subscript]Copy the code
The index value starts at 0 and -1 starts at the end.
The plus sign + is the concatenation of the string, the asterisk * is the number of times the string was copied. Examples are as follows:
The instance
str = 'Runoob'
print (str) # output string
print (str[0:-1]) Print all characters from the first to the penultimate
print (str[0]) # Print the first character of the string
print (str[2:5]) # print characters from the third to the fifth
print (str[2:]) # print all characters from the third
print (str * 2) Print the string twice
print (str + "TEST") # connect stringCopy the code
Executing the above program produces the following results:
Runoob
Runoo
R
noo
noob
RunoobRunoob
RunoobTESTCopy the code
Python uses the backslash (\) to escape special characters. If you don’t want the backslash to escape, you can add an R to the front of the string to indicate the original string:
>>> print('Ru\noob')
Ru
oob
>>> print(r'Ru\noob')
Ru\noob
>>> Copy the code
In addition, a backslash (\) can be used as a line continuation, indicating that the next line is a continuation of the previous line. You can also use “””…” “” or” ‘… “” spans multiple lines.
Note that Python has no separate character types; a character is a string of length 1.
The instance
>>>word = 'Python'
>>> print(word[0], word[5])
P n
>>> print(word[-1], word[-6])
n PCopy the code
Unlike C strings, Python strings cannot be altered. Assigning a value to an index location such as word[0] = ‘m’ causes an error.
Note:
- 1, backslashes can be used to escape, using r to prevent backslashes from escaping.
- 2. Strings can be concatenated with the + operator and repeated with the * operator.
- 3. Strings in Python are indexed in two ways, starting with 0 from left to right and -1 from right to left.
- 4. Strings in Python cannot be changed.
7. ()
List is the most frequently used data type in Python.
Lists can complete the data structure implementation of most collection classes. The types of elements in a list can be different, it supports numbers, and strings can even contain lists (so-called nesting).
A list is a comma-separated list of elements written between square brackets [].
Like strings, lists can be indexed and truncated, and truncated lists return a new list containing the desired elements.
The syntax format for list intercepts is as follows:
Variable [header subscript: tail subscript]Copy the code
The index value starts at 0 and -1 starts at the end.
The plus sign + is the list join operator, and the asterisk * is a repeat operation. Examples are as follows:
The instance
list = [ 'abcd', 786, 2.23,'runoob', 70.2] tinyList = [123,'runoob']
print (list) Print the complete list
print (list[0]) Print the first element of the list
print (list[1:3]) # Output from the second to the third element
print (list[2:]) Output all elements starting with the third element
print (tinylist * 2) Print the list twice
print (list + tinylist) # list of connectionsCopy the code
The output of the above example is as follows:
['abcd', 786, 2.23, 'runoob', 70.2]
abcd
[786, 2.23]
[2.23, 'runoob'70.2], [123,'runoob', 123, 'runoob']
['abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob']Copy the code
Unlike Python strings, elements in a list can be changed:
The instance
>>>a = [1, 2, 3, 4, 5, 6]
>>> a[0] = 9
>>> a[2:5] = [13, 14, 15]
>>> a
[9, 2, 13, 14, 15, 6]
>>> a[2:5] = [] # set the corresponding element value to []
>>> a
[9, 2, 6]Copy the code
List has many built-in methods, such as append(), pop(), and more, which we’ll cover later.
Note:
- 1. List is written between square brackets, with elements separated by commas.
- 2. Like strings, lists can be indexed and sliced.
- 3. Lists can be concatenated using the + operator.
- 4. Elements in a List can be changed.
Python list interception can take a third argument that intercepts the step size. The following example intercepts a string at indexes 1 through 4 and sets the step size to 2 (one place apart) :
If the third argument is negative to indicate reverse reading, the following example is used to reverse the string:
The instance
def reverseWords(input):
# String delimiters with Spaces to separate words into lists
inputWords = input.split("")
# flip string
List = [1,2,3,4]
# list[0]=1, list[1]=2, and -1 =1
# inputWords[-1::-1] takes three parameters
The first argument -1 represents the last element
The second argument is empty, indicating that the list is moved to the end
The third parameter is the step size, -1 indicates the reverse
inputWords=inputWords[-1::-1]
# recombine strings
output = ' '.join(inputWords)
return output
if __name__ == "__main__":
input = 'I like runoob'
rw = reverseWords(input)
print(rw)Copy the code
The output is:
runoob like ICopy the code
8.Tuple
Tuples are similar to lists except that the elements of a tuple cannot be modified. Tuples are written in parentheses (), with elements separated by commas.
Element types in tuples can also be different:
The instance
tuple = ( 'abcd', 786, 2.23,'runoob', 70.2) tinytuple = (123,'runoob')
print (tuple) Output the full tuple
print (tuple[0]) Print the first element of the tuple
print (tuple[1:3]) The output starts from the second element to the third element
print (tuple[2:]) Output all elements starting with the third element
print (tinytuple * 2) Print the tuple twice
print (tuple + tinytuple) # connect tuplesCopy the code
The output of the above example is as follows:
('abcd', 786, 2.23, 'runoob', 70.2)
abcd
(786, 2.23)
(2.23, 'runoob'70.2), (123,'runoob', 123, 'runoob')
('abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob')Copy the code
Tuples are similar to strings in that they can be indexed and the subscript index starts at 0, with -1 being the position starting from the end. Interception is also possible (see above, not described here).
Instead, you can think of a string as a special kind of tuple.
The instance
>>>tup = (1, 2, 3, 4, 5, 6)
>>> print(tup[0])
1
>>> print(tup[1:5])
(2, 3, 4, 5)
>>> tup[0] = 11 It is illegal to modify a tuple element
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>Copy the code
Although the element of a tuple is immutable, it can contain mutable objects, such as a list list.
Constructing tuples with 0 or 1 elements is special, so there are some additional syntax rules:
tup1 = () # empty tuple
tup2 = (20,) An element that requires a comma after the elementCopy the code
Strings, lists, and tuples are all sequences.
Note:
- 1. As with strings, elements of tuples cannot be modified.
- 2. Tuples can also be indexed and sliced in the same way.
- 3. Note the special syntax for constructing tuples with 0 or 1 elements.
- 4. Tuples can also be concatenated using the + operator.
9.Set
Set is made up of one or a number of different shapes and sizes of the whole, the things or objects that constitute the set are called elements or members.
The basic functionality is membership testing and removing duplicate elements.
You can use curly braces {} or the set() function to create a collection. Note: To create an empty collection, you must use set() instead of {}, because {} is used to create an empty dictionary.
Create format:
parame = {value01,value02,... } orset(value)Copy the code
The instance
student = {'Tom'.'Jim'.'Mary'.'Tom'.'Jack'.'Rose'}
print(student) # output set, duplicate elements are automatically removed
# Member test
if 'Rose' in student :
print('Rose is in the set ')
else :
print('Rose is not in the set ')
# set can perform set operations
a = set('abracadabra')
b = set('alacazam')
print(a)
print(a - b) The difference between a and b
print(a | b) # union of a and b
print(a & b) # Intersection of A and B
print(a ^ b) The elements of a and B that do not coexistCopy the code
The output of the above example is as follows:
{'Mary'.'Jim'.'Rose'.'Jack'.'Tom'} Rose in the collection {'b'.'a'.'c'.'r'.'d'}
{'b'.'d'.'r'}
{'l'.'r'.'a'.'c'.'z'.'m'.'b'.'d'}
{'a'.'c'}
{'l'.'r'.'z'.'m'.'b'.'d'}Copy the code
10.Dictionary
Dictionaries are another very useful built-in data type in Python.
Lists are ordered collections of objects, dictionaries are unordered collections of objects. The difference is that elements in dictionaries are accessed by keys, not by offsets.
A dictionary is a mapping type. A dictionary is identified by {}. It is an unordered set of keys: values.
Keys must be of immutable type.
A key must be unique in the same dictionary.
The instance
dict = {}
dict['one'] = "1 - Rookie Tutorial"
dict[2] = "2 - Rookie tools"
tinydict = {'name': 'runoob'.'code': 1,'site': 'www.runoob.com'}
print (dict['one']) # output the value with the key 'one'
print (dict[2]) Print the value of key 2
print (tinydict) Print the complete dictionary
print (tinydict.keys()) Print all keys
print (tinydict.values()) Print all valuesCopy the code
The output of the above example is as follows:
1 - Rookie tutorial 2 - Rookie tools {'name': 'runoob'.'code': 1, 'site': 'www.runoob.com'}
dict_keys(['name'.'code'.'site'])
dict_values(['runoob', 1, 'www.runoob.com'])Copy the code
The dict() constructor builds a dictionary directly from a sequence of key-value pairs as follows:
The instance
>>>dict([('Runoob', 1), ('Google', 2), ('Taobao'And 3)]) {'Taobao': 3.'Runoob': 1, 'Google': 2}
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
>>> dict(Runoob=1, Google=2, Taobao=3)
{'Runoob': 1, 'Google': 2.'Taobao': 3}Copy the code
In addition, dictionary types have built-in functions such as clear(), keys(), values(), and so on.
Note:
- 1. A dictionary is a mapping type whose elements are key-value pairs.
- 2. Dictionary keywords must be immutable and cannot be repeated.
- Create an empty dictionary using {}.
11.Python data type conversion
Sometimes, we need to convert data to built-in types. To convert data types, you just need to use the data type as the function name.
The following built-in functions perform conversions between data types. These functions return a new object representing the value of the transformation.
function | describe |
---|---|
int(x [,base]) |
Convert x to an integer |
float(x) |
Convert x to a floating point number |
complex(real [,imag]) |
Create a complex number |
str(x) |
Convert object X to a string |
repr(x) |
Convert object X to an expression string |
eval(str) |
Evaluates a valid Python expression in a string and returns an object |
tuple(s) |
Converts the sequence S to a tuple |
list(s) |
Convert the sequence S to a list |
set(s) |
Convert to a mutable set |
dict(d) |
Create a dictionary. D must be a sequence of (key, value) tuples. |
frozenset(s) |
To an immutable set |
chr(x) |
Converts an integer to a character |
ord(x) |
Converts a character to its integer value |
hex(x) |
Converts an integer to a hexadecimal string |
oct(x) |
Converts an integer to an octal string |
Python3 annotation
Make sure to use the correct style for modules, functions, methods, and inline comments
Comments in Python include single-line and multi-line comments:
Single-line comments in Python start with #, for example:
Multi-line comments enclose comments with three single quotation marks “” or three double quotation marks “””, for example:
1. Single quotes (” “)
' ''This is a multi-line comment with three single quotes.'' '
print("Hello, World!")Copy the code
2. Double quotation marks (“””)
"""This is a multi-line comment with three double quotation marks."""
print("Hello, World!")Copy the code
Python3 operator
1. What are operators?
This section focuses on Python operators. Let’s take a simple example: 4 +5 = 9. In this example, 4 and 5 are called operands, and “+” is the operator.
The Python language supports the following types of operators:
- Arithmetic operator
- Compare (relational) operators
- The assignment operator
- Logical operator
- An operator
- Member operator
- Identity operator
- Operator priority
Let’s take a look at Python operators one by one.
2. Python arithmetic operators
Assume that variable A is 10 and variable B is 21:
The operator | describe | The instance |
---|---|---|
+ | Add – Add two objects | A + b Output 31 |
– | Subtract – to get a negative number or subtract something from something else | A-b The output is -11 |
* | Multiply – Multiply two numbers together or return a string that has been repeated several times | A * b displays 210 |
/ | Over minus x over y | B/a The output is 2.1 |
% | Modulo – Returns the remainder of the division | B % a Output 1 |
** | Power – Returns x to the y power | A times b is 10 to the 21 |
// | Take a divisor – take an integer down near the divisor |
|
The following example demonstrates the operation of all Python arithmetic operators:
Instance (Python 3.0 +)
#! /usr/bin/python3
a = 21
b = 10
c = 0
c = a + b
print ("The value of 1-c is:", c)
c = a - b
print ("The value of 2-c is:, c)
c = a * b
print ("The value of 3-c is:, c)
c = a / b
print ("The value of 4-c is:, c)
c = a % b
print ("The value of 5-c is:, c)
Change variables A, B, and c
a = 2
b = 3
c = a**b
print ("The value of 6-c is:, c)
a = 10
b = 5
c = a//b
print ("The value of 7-c is:, c)Copy the code
The output of the above example is as follows:
For 1-C, the value is 31. For 2-C, the value is 11. For 3-C, the value is 210. For 4-C, the value is 2.1. For 5-C, the value is 1Copy the code
3. Python comparison operators
Assume that variable A is 10 and variable B is 20:
The operator | describe | The instance |
---|---|---|
= = | Equal – Whether the objects are equal | Return False. |
! = | Not equal – Compares whether two objects are not equal | (a ! = b) returns True. |
> | Greater than – Returns whether x is greater than y | A > b returns False. |
< | Less than – Returns whether x is less than y. All comparison operators return 1 for true and 0 for false. This is equivalent to the special variables True and False respectively. Note that the variable names are capitalized. | (a < b) returns True |
> = | Greater than or equal to – Returns whether x is greater than or equal to y. | (a >= b) returns False. |
< = | Less than or equal to – Returns whether x is less than or equal to y. | (a <= b) returns True. |
The following example demonstrates the operation of all Python comparison operators:
Instance (Python 3.0 +)
#! /usr/bin/python3
a = 21
b = 10
c = 0
if ( a == b ):
print ("1 minus a is equal to B")
else:
print ("1 - A is not equal to B.")
if( a ! = b ):print ("2-a is not equal to B.")
else:
print ("2 minus a is equal to B")
if ( a < b ):
print ("3-A is less than B")
else:
print ("3 minus a is greater than or equal to B.")
if ( a > b ):
print ("4-A is greater than B")
else:
print ("4 minus a is less than or equal to B.")
Change the values of variables A and b
a = 5;
b = 20;
if ( a <= b ):
print ("5 minus a is less than or equal to B.")
else:
print ("5-A is greater than B")
if ( b >= a ):
print ("6 minus b is greater than or equal to a.")
else:
print ("6 minus b is less than a")Copy the code
The output of the above example is as follows:
1 minus a is not equal to b 2 minus a is not equal to b 3 minus a is greater than or equal to b 4 minus A is greater than or equal to b 5 minus a is less than or equal to b 6 minus b is greater than or equal to aCopy the code
4. Python assignment operator
Assume that variable A is 10 and variable B is 20:
The operator | describe | The instance |
---|---|---|
= | A simple assignment operator | C = a + b Assigns the result of a + b to c |
+ = | The addition assignment operator | C plus a is the same thing as c is equal to c plus a |
– = | The subtraction assignment operator | C minus a is the same thing as c minus a |
* = | Multiplication assignment operator | C times a is the same thing as c times a |
/ = | The division assignment operator | C/a is the same thing as c = c/a |
% = | Take the modulo assignment operator | C %= a is the same thing as c = c % a |
* * = | Power assignment operator | C **= a is the same thing as c = c ** A |
/ / = | Takes the divisible assignment operator | C //= a is equivalent to c = c // a |
: = | Walrus operator that assigns values to variables inside expressions.New operator for Python3.8. |
In this example, the assignment expression avoids calling len() twice:
|
The following example demonstrates all of Python’s assignment operators:
Instance (Python 3.0 +)
#! /usr/bin/python3
a = 21
b = 10
c = 0
c = a + b
print ("The value of 1-c is:", c)
c += a
print ("The value of 2-c is:, c)
c *= a
print ("The value of 3-c is:, c)
c /= a
print ("The value of 4-c is:, c)
c = 2
c %= a
print ("The value of 5-c is:, c)
c **= a
print ("The value of 6-c is:, c)
c //= a
print ("The value of 7-c is:, c)Copy the code
The output of the above example is as follows:
If the value of 1-C is 31, that of 2-C is 52, that of 3-C is 1092, that of 4-C is 52.0, that of 5-C is 2, that of 6-C is 2097152, that of 7-C is 99864Copy the code
5. Python bitwise operators
Bitwise operators evaluate numbers as if they were binary. Bitwise operations in Python are as follows:
In the following table, variable A is 60 and variable B is 13 in binary format:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011Copy the code
The operator | describe | The instance |
---|---|---|
& | Bitwise and operator: Two values involved in the operation, the result of which is 1 if both corresponding bits are 1, and 0 otherwise | (a & b) Output 12, binary interpretation: 0000 1100 |
| | Bitwise or operator: if either of the two corresponding binary digits is 1, the result bit is 1. | (a | b) output 61, binary interpretation: 0011 1101 |
^ | Bitwise xor operator: When two corresponding binary bits differ, the result is 1 | (a ^ b) 49, binary interpretation: 0011 0001 |
~ | Bitwise invert operator: Invert each binary bit of data, that is, changing 1 to 0 and 0 to 1. ~x is similar to -x-1 | (~a) Output result -61, binary interpretation: 1100 0011, in the form of a signed binary number’s complement. |
<< | Left shift operator: the binary of the operand moves several bits to the left. The number to the right of “<<” specifies the number of bits to move. The high digit is discarded and the low digit is filled with 0. | A << 2 output result 240, binary interpretation: 1111 0000 |
>> | Right shift operator: Moves all the binary digits of the operand to the left of “>>” several right, and the number to the right of “>>” specifies the number of digits to move | A >> 2 Output 15, binary interpretation: 0000 1111 |
The following example demonstrates the operation of all Python bit-operators:
Instance (Python 3.0 +)
#! /usr/bin/python3
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0
c = a & b; # 12 = 0000 1100
print ("The value of 1-c is:", c)
c = a | b; # 61 = 0011 1101
print ("The value of 2-c is:, c)
c = a ^ b; # 49 = 0011 0001
print ("The value of 3-c is:, c)
c = ~a; # -61 = 1100 0011
print ("The value of 4-c is:, c)
c = a << 2; # 240 = 1111 0000
print ("The value of 5-c is:, c)
c = a >> 2; # 15 = 0000 1111
print ("The value of 6-c is:, c)Copy the code
The output of the above example is as follows:
The value of 1-C is 12. The value of 2-C is 61. The value of 3-C is 49. The value of 4-C is -61Copy the code
6. Python logical operators
The Python language supports logical operators, assuming variables A are 10 and b is 20:
The operator | Logical expression | describe | The instance |
---|---|---|---|
and | x and y | Boolean “and” – x and y returns False if x is False, otherwise it returns the computed value of y. | A and b return 20. |
or | x or y | Boolean “or” – it returns the value of x if x is True, otherwise it returns the calculated value of y. | A or b returns 10. |
not | not x | Boolean “not” – returns False if x is True. If x is False, it returns True. | Not (a and b) returns False |
The output of the above example is as follows:
Instance (Python 3.0 +)
#! /usr/bin/python3
a = 10
b = 20
if ( a and b ):
print ("1 - Variables A and b are true")
else:
print ("1 - One of the variables A and B is not true")
if ( a or b ):
print ("2 - both variables a and b are true, or one of them is true")
else:
print ("2 - the variables a and B are not true")
Change the value of variable A
a = 0
if ( a and b ):
print ("3 - Variables A and b are true")
else:
print ("3 - One of the variables A and B is not true")
if ( a or b ):
print ("4 - both variables a and b are true, or one of them is true")
else:
print ("4 - Variables a and B are not true")
if not( a and b ):
print ("5 - Both variables a and b are false, or one of them is false")
else:
print ("5 - Variables A and b are true")Copy the code
The output of the above example is as follows:
1 - The variables A and B aretrue2 - The variables A and b aretrue, or one of the variables istrue3 - One of the variables A and B does nottrue4 - The variables A and B aretrue, or one of the variables istrue5 - The variables A and B arefalse, or one of the variables isfalseCopy the code
7. Python member operators
In addition to some of the above operators, Python also supports member operators. The test instance contains a series of members, including strings, lists, or tuples.
The operator | describe | The instance |
---|---|---|
in | Returns True if a value is found in the specified sequence, False otherwise. | X is in the y sequence and returns True if x is in the y sequence. |
not in | Returns True if no value was found in the specified sequence, False otherwise. | X is not in the y sequence, and returns True if x is not in the y sequence. |
The following example demonstrates the operation of all Python member operators:
Instance (Python 3.0 +)
#! /usr/bin/python3
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print ("1 - Variable A in the given list list")
else:
print ("1 - Variable A is not in the given list list")
if ( b not in list ):
print ("2 - variable B is not in the given list list")
else:
print ("2 - variable B in the given list list")
Change the value of variable A
a = 2
if ( a in list ):
print ("3 - Variable A in the given list list")
else:
print ("3 - Variable A is not in the given list list")Copy the code
The output of the above example is as follows:
1 - variable A is not in a given list 2 - variable B is not in a given list 3 - variable A is in a given list listCopy the code
8. Python identity operators
The identity operator is used to compare the storage units of two objects
The operator | describe | The instance |
---|---|---|
is | Is determines whether two identifiers refer to an object | x is y, similar toid(x) == id(y)Returns True if the same object is referenced, False otherwise |
is not | Is not determines whether two identifiers refer to different objects | x is not y, similar toid(a) ! = id(b). Returns True if not the same object is referenced, False otherwise. |
Note: The id() function is used to get the memory address of an object.
The following example demonstrates the operation of all of Python’s identity operators:
Instance (Python 3.0 +)
a = 20
b = 20
if ( a is b ):
print ("1-A and B have the same markings.")
else:
print ("1-A and B do not have the same identification.")
if ( id(a) == id(b) ):
print ("2-A and B have the same markings.")
else:
print ("2-A and B do not have the same identification.")
Change the value of variable b
b = 30
if ( a is b ):
print ("3-A and B have the same markings.")
else:
print ("3-A and B do not have the same identification.")
if ( a is not b ):
print ("4-A and B do not have the same identification.")
else:
print ("4-A and B have the same markings.")Copy the code
The output of the above example is as follows:
1 - A and B have the same identifier. 2 - A and B have the same identifier. 3 - A and B do not have the same identifierCopy the code
Difference between is and == :
Is is used to determine whether two variable reference objects are the same, and == is used to determine whether the values of reference variables are the same.
>>>a = [1, 2, 3] >>> b = a >>> b is a True >>> b == a True >>> b = a[:] >>> b is a False >>> b == a True
9. Python operator precedence
The following table lists all operators from highest to lowest priority:
The operator | describe |
---|---|
** | Index (highest priority) |
~ + – | Bitwise flip, unary plus and minus (the last two methods are called +@ and -@) |
% * / / / | Multiply, divide, take modulus and take exact division |
+ – | Addition subtraction |
>> << | Shift right, shift left operator |
& | A ‘AND’ |
^ | | An operator |
< = < > > = | Comparison operator |
= =! = | Equal operator |
= %= /= //= -= += *= **= | The assignment operator |
is is not | Identity operator |
in not in | Member operator |
not and or | Logical operator |
The following example demonstrates the operation of all Python operator priorities:
Instance (Python 3.0 +)
#! /usr/bin/python3
a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d So this is equal to 30 times 15 over 5
print ((a + b) * c/d, e)
e = ((a + b) * c) / d So this is equal to 30 times 15 over 5
print ((a + b) * c)/d, e)
e = (a + b) * (c / d); # (30) * (15/5)
print ((a + b) * (c/d), e)
e = a + (b * c) / d; # 20 + (150/5)
print ("A + (b * c)/d", e)Copy the code
The output of the above example is as follows:
(a + b) * c/d: 90.0 ((a + b) * c)/d: 90.0 (a + b) * (c/d) : 90.0 a + (b * c)/d: 50.0Copy the code
Note:Pyhton3 no longer supports the <> operator. = instead, if you must use the comparison operator, you can use the following:
>>> from __future__ import barry_as_FLUFL >>> 1 <> 2 TrueCopy the code
5, Python3 (Number)
Python numeric data types are used to store numeric values.
Data types are not allowed to change, which means that if you change the value of a numeric data type, memory space will be reallocated.
The following instance will create the Number object when the variable is assigned:
var1 = 1
var2 = 10Copy the code
You can also use the DEL statement to remove references to some numeric objects.
The syntax for a del statement is:
del var1[,var2[,var3[....,varN]]]Copy the code
You can remove references to single or multiple objects by using the DEL statement, for example:
del var
del var_a, var_bCopy the code
Python supports three different numeric types:
- Int – often referred to as an integer or integer, is a positive or negative integer without a decimal point. Python3 integers are unlimited in size and can be used as Long, so Python3 does not have a Python2 Long.
- Floating point – Floating point consists of integer and decimal parts. Floating point can also be represented by scientific notation (2.5e2 = 2.5 x 102 = 250)
- Complex number ((complex)) – The complex number consists of the real and imaginary parts and can be represented by a + BJ, or complex(a,b). The real part A and imaginary part B of the complex number are floating-point.
We can use hexadecimal and octal numbers to represent integers:
>>> number = 0xA0F # hex
>>> number
2575
>>> number=0o37 # octal
>>> number
31Copy the code
int | float | complex |
---|---|---|
10 | 0.0 | 3.14 j. |
100 | 15.20 | 45.j |
– 786. | 21.9 | 9.322 e-36 j |
080 | 32.3 e+18 | .876j |
– 0490. | – 90. | -.6545+0J |
-0x260 | 32.54 e100 | 3e+26J |
0x69 | 70.2 e-12 | 4.53 e-7 j |
- Python supports complex numbers, which consist of both the real and imaginary parts and can be represented by a + bj, or complex(a,b). Both the real and imaginary parts of complex numbers are floating-point.
1. Python numeric type conversion
Sometimes, we need to convert data to built-in types. To convert data types, you just need to use the data type as the function name.
-
Int (x) converts x to an integer.
-
Float (x) converts x to a floating point number.
-
Complex (x) converts x to a complex number with a real part of x and an imaginary part of 0.
-
Complex (x, y) converts x and y to a complex number with the real part x and the imaginary part y. X and y are numerical expressions.
The following example converts the floating point variable A to an integer:
>>> a = 1.0
>>> int(a)
1Copy the code
2. Python number operations
The Python interpreter can be used as a simple calculator. You can type an expression into the interpreter, and it will output the value of the expression.
The syntax for expressions is straightforward: +, -, *, and /, as in other languages such as Pascal or C. Such as:
> > > 2 + 2 4 > > > 50-5 * 6 20 > > > 5.0 (50-5 * 6) / 4 > > > 8/5Always return a floating point number
1.6Copy the code
Note: Floating-point calculations may produce different results on different machines.
In integer division, the division/always returns a floating-point number. If you just want to get the result of an integer and discard the possible fraction, you can use the operator // :
>>> 17 / 3 Integer division returns floating point type5.66666666667 >>> >>> 17 // 3Integer division returns the rounded down result5 >>> 17%3The # % operator returns the remainder of the division2 >>> 5 times 3 + 2 17Copy the code
Note: // is not necessarily an integer number, it depends on the data type of the numerator in the denominator.
>>> 7//2
3
>>> 7.0//2
3.0
>>> 7//2.0
3.0
>>> Copy the code
The equal sign = is used to assign values to variables. After assignment, the interpreter does not display any results except for the next prompt.
>>> width = 20
>>> height = 5*9
>>> width * height
900Copy the code
Python can use the ** operation for exponentiation:
> > > 5 * * 2# 5 squared
25
>>> 2 ** 7 Two PI to the seventh
128Copy the code
A variable must be “defined” (that is, given a value) before it can be used, otherwise an error occurs:
>>> n Try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not definedCopy the code
A combination of different types of numbers converts integers to floating point numbers:
>>> 3 * 3.75/1.5 7.5 >>> 7.0/2 3.5Copy the code
In interactive mode, the last output expression result is assigned to the variable _. Such as:
>>> Tax = 12.5/100 >>> Price = 100.50 >>> Price * tax 12.5625 >>> Price + _ 113.0625 >>> Round (_, 2) 113.06Copy the code
Here, the _ variable should be treated as read-only by the user.
3. Mathematical functions
function | Return value (Description) |
---|---|
abs(x) | Returns the absolute value of a number, such as ABS (-10) returns 10 |
ceil(x) | Returns the uppermost integer of a number, such as math.ceil(4.1) returns 5 |
cmp(x, y) |
Returns -1 if x < y, 0 if x == y, and 1 if x > y.Python 3 is deprecated and replaced with (x>y)-(x<y). |
exp(x) | Return e to the x power (ex), such as math.exp(1) returns 2.718281828459045 |
fabs(x) | Returns the absolute value of a number, such as math.fabs(-10) returns 10.0 |
floor(x) | Returns the rounded integer of a number, such as math.floor(4.9) returns 4 |
log(x) | For example,math.log(math.e) returns 1.0 and math.log(100,10) returns 2.0 |
log10(x) | Returns the logarithm of x in base 10, as math.log10(100) returns 2.0 |
max(x1, x2,…) | Returns the maximum value of the given argument, which can be a sequence. |
min(x1, x2,…) | Returns the minimum value of the given argument, which can be a sequence. |
modf(x) | Returns the integer and decimal parts of x, both of which have the same numeric symbol as x. The integer part is represented as a floating point. |
pow(x, y) | X **y. |
round(x [,n]) | Returns the rounded value of the floating point number x, representing the number of digits rounded to the decimal point if n is given. |
sqrt(x) | Returns the square root of the number x. |
Random number function
Random numbers can be used in mathematics, games, security and other fields, and are often embedded in algorithms to improve the efficiency of algorithms and improve the security of programs.
Python contains the following common random number functions:
function | describe |
---|---|
choice(seq) | Select an element from the sequence at random, such as random.choice(range(10)), an integer from 0 to 9. |
randrange ([start,] stop [,step]) | Gets a random number from a set in the specified range that increases by the specified cardinality, with the cardinality default being 1 |
random() | Randomly generates the next real number in the range [0,1]. |
seed([x]) | Change the seed of the random number generator. If you don’t know how it works, you don’t have to specify the seed; Python will select the seed for you. |
shuffle(lst) | Sort all the elements of the sequence randomly |
uniform(x, y) | Randomly generate the next real number in the range [x,y]. |
5. Trigonometric functions
Python includes the following trigonometric functions:
function | describe |
---|---|
acos(x) | Returns the arccosine radian value of x. |
asin(x) | Returns the arcsine radian value of x. |
atan(x) | Returns the arctangent radian value of x. |
atan2(y, x) | Returns the arctangent of the given X and Y coordinates. |
cos(x) | Returns the cosine of x radians. |
hypot(x, y) | Return the Euclidean norm SQRT (x*x + y*y). |
sin(x) | The sine of x radians returned. |
tan(x) | Returns the tangent of x radians. |
degrees(x) | Convert radians to angles, such as degrees(math.pi/2), and return 90.0 |
radians(x) | Convert the Angle to radians |
6. Mathematical constants
constant | describe |
---|---|
pi | Mathematical constant PI (the value of PI, usually represented by π) |
e | The mathematical constant e, e is the natural constant (natural constant). |
Python3 Character string
Strings are the most commonly used data type in Python. We can use quotes (‘ or “) to create strings.
Creating a string is as simple as assigning a value to a variable. Such as:
1. Python accesses values in strings
Python does not support single-character types, which are also used as strings in Python.
Python accesses substrings, which can be intercepted using square brackets, as shown in the following example:
Instance (Python 3.0 +)
#! /usr/bin/python3
var1 = 'Hello World! '
var2 = "Runoob"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])Copy the code
The execution results of the above examples:
var1[0]: H
var2[1:5]: unooCopy the code
3. Python string updates
You can take part of a string and concatenate it with other fields, as shown in the following example:
Instance (Python 3.0 +)
#! /usr/bin/python3
var1 = 'Hello World! '
print ("Updated string:", var1[:6] + 'Runoob! ')Copy the code
The above example execution results
Updated string: Hello Runoob!Copy the code
4. Python escape characters
Python escapes characters with a backslash (\) when special characters are needed in a character. The following table:
Escape character | describe |
---|---|
\(at the end of the line) | Line continuation operator |
\ \ | Backslash notation |
\ ‘ | Single quotes |
\” | Double quotation marks |
\a | Ring the bell |
\b | Backspace (Backspace) |
\ 000 | empty |
\n | A newline |
\v | Vertical TAB character |
\t | Horizontal tabs |
\r | enter |
\f | Change the page |
\oyy | Octal number,yyRepresents a character, for example:\o12Stands for newline, where o is a letter, not the number 0. |
\xyy | A hexadecimal number, yy represents a character, for example, \x0a represents a newline |
\other | Other characters are printed in normal format |
5. Python string operators
The following table instance variable a is the string “Hello” and variable B is the string “Python” :
The operator | describe | The instance |
---|---|---|
+ | String conjunction | A + b: HelloPython |
* | Repeat output string | A *2 Output: HelloHello |
[] | Gets characters in a string by index | A [1] output resultse |
[:] | Intercepts a portion of the string, followingLeft closed right awayAs a rule, STR [0,2] does not contain a third character. | A [1:4] output resultsell |
in | Member operator – Returns True if the string contains the given character | ‘H’ in aOutput True |
not in | Member operator – Returns True if the string does not contain the given character | ‘M’ not in aOutput True |
r/R | Raw strings – Raw strings: All strings are used literally, without escaping special or printable characters. Raw strings have almost exactly the same syntax as regular strings, except that the first quotation mark of the string is preceded by the letter R (which can be uppercase and lowercase). |
|
% | Format string | Look at the next section. |
Instance (Python 3.0 +)
#! /usr/bin/python3
a = "Hello"
b = "Python"
print("A + b output result:", a + b)
print("A * 2 output result:", a * 2)
print("A [1] Output result:, a[1])
print("A [1:4] Output result:", a[1:4])
if( "H" in a) :
print("H is in variable A.")
else :
print("H is not in variable A.")
if( "M" not in a) :
print("M is not in variable A.")
else :
print("M is in variable A.")
print (r'\n')
print (R'\n')Copy the code
The output result of the above example is:
Hellohelloa [1] e a[1:4] Ell H is in variable A and M is not in variable A \n \nCopy the code
6. Python string formatting
Python supports output of formatted strings. Although this can involve very complex expressions, the most basic use is to insert a value into a string with the string formatter %s.
String formatting in Python uses the same syntax as the sprintf function in C.
Instance (Python 3.0 +)
#! /usr/bin/python3
print ("My name is % S and I am % D!" % ('Ming', 10))Copy the code
The output of the above example is as follows:
My name is Xiaoming and I am 10 years old!Copy the code
Python string formatting notation:
Operator, | describe |
---|---|
%c
|
Format characters and their ASCII codes
|
%s
|
Formatted string
|
%d
|
Formatted integer
|
%u
|
Format an unsigned integer
|
%o
|
Format an unsigned octal number
|
%x
|
Format an unsigned hexadecimal number
|
%X
|
Formatted unsigned hexadecimal number (uppercase)
|
%f
|
Format a floating-point number that specifies the precision after the decimal point
|
%e
|
Format floating point numbers with scientific notation
|
%E
|
Same as %e, uses scientific notation to format floating-point numbers
|
%g
|
Short for %f and %e
|
%G
|
Short for %f and %E
|
%p
|
Format the address of a variable with a hexadecimal number
|
Formatting operator auxiliary instructions:
symbol | function |
---|---|
* | Define width or decimal precision |
– | Use it for left alignment |
+ | Display a plus sign (+) before a positive number |
<sp> | Display Spaces before positive numbers |
# | Display zero before octal numbers (‘0’) and either ‘0x’ or ‘0x’ before hexadecimal numbers (depending on whether ‘x’ or ‘x’ is used) |
0 | The number displayed is preceded by a ‘0’ instead of the default space |
% | ‘%%’ prints a single ‘%’ |
(var) | Mapping variables (dictionary parameters) |
m.n. | M is the minimum total width to display and n is the number of decimal places (if available) |
Python2.6 has added a str.format() function to format strings, which enhances string formatting.
7. Python triple quotes
Python triple quotes allow a string to span multiple lines. Strings can contain newlines, tabs, and other special characters. Instance as follows
Instance (Python 3.0 +)
#! /usr/bin/python3
para_str = """This is an example of a multi-line string which can be used with TAB (\t). A newline character [\n] can also be used. """
print (para_str)Copy the code
The execution results of the above examples are as follows:
This is an example of a multi-line string and a multi-line string can use the TAB () character. A newline character [] can also be used.Copy the code
Triple quotation marks free programmers from the quagmire of quotation marks and special strings and keep small chunks of strings in the so-called WYSIWYG format all the way through.
A typical use case is when you need a piece of HTML or SQL to combine with strings. Special string escapes can be cumbersome.
errHTML = ' ''
<HTML><HEAD><TITLE>
Friends CGI Demo</TITLE></HEAD>
<BODY><H3>ERROR</H3>
<B>%s</B><P>
<FORM><INPUT TYPE=button VALUE=Back
ONCLICK="window.history.back()"></FORM>
</BODY></HTML>
'' '
cursor.execute(' '' CREATE TABLE users ( login VARCHAR(8), uid INTEGER, prid INTEGER) '' ')Copy the code
8. f-string
F-string was added later than python3.6 and is called a literal format string, which is the new format string syntax.
Previously we used to use a percent sign (%):
The instance
>>> name = 'Runoob'
>>> 'Hello %s' % name'Hello Runoob'Copy the code
In the f-string format, a string begins with f, followed by a string. The expression in the string is wrapped in curly braces {}, which replaces the evaluated value of a variable or expression. Example:
The instance
>>> name = 'Runoob'
>>> f'Hello {name}' # replace variable
>>> f'{1 + 2}' # use the expression '3'
>>> w = {'name': 'Runoob'.'url': 'www.runoob.com'}
>>> f'{w["name"]}: {w["url"]}''Runoob: www.runoob.com'Copy the code
This way it’s much easier to decide whether to use %s or % D.
In Python 3.8, the = symbol can be used to concatenate an operational expression with a result:
The instance
>>> x = 1
>>> print(f'{x+1}') # Python 3.62
>>> x = 1
>>> print(f'{x+1=}') '# Python 3.8 x + 1 = 2'Copy the code
9. Unicode strings
In Python2, normal strings are stored as 8-bit ASCII, while Unicode strings are stored as 16-bit Unicode strings, which can represent a wider set of characters. The syntax used is to prefix a string with u.
In Python3, all strings are Unicode strings.
10. Python’s string built-in functions
Python’s common built-in functions for strings are as follows:
The serial number | Methods and Description |
---|---|
1 |
Capitalize () converts the first character of a string to uppercase |
2 |
center(width, fillchar) Returns a string with the specified width in the middle, fillchar is the filled character, default is space. |
3 |
count(str, beg= 0,end=len(string)) Return the number of occurrences of STR in string, or within the specified range if beg or end is specified |
4 |
bytes.decode(encoding=”utf-8″, errors=”strict”) There is no decode method in Python3, but we can use the decode() method of a bytes object to decode a given bytes object, which can be returned by str.encode(). |
5 |
encode(encoding=’UTF-8′,errors=’strict’) Encoding strings in the encoding format specified for encoding. If errors occur, a ValueError is raised by default, unless errors specify ‘ignore’ or ‘replace’. |
6 |
Endswith (suffix, beg=0, end=len(string)) endswith(suffix, beg=0, end=len(string)) checks if the string endswith obj, if beg or end is specified, checks if the specified range endswith obj, True if so, False otherwise. |
7 |
expandtabs(tabsize=8) Convert the TAB character in string to a space. The default TAB character is 8 Spaces. |
8 |
find(str, beg=0, end=len(string)) Checks if STR is contained in the string, in the specified range if the ranges beg and end are specified, and -1 if it is |
9 |
index(str, beg=0, end=len(string)) Like the find() method, except that an exception is raised if STR is not in the string. |
10 |
isalnum() Returns True if the string has at least one character and all characters are letters or numbers, False otherwise |
11 |
isalpha() Return True if the string has at least one character and all characters are letters, False otherwise |
12 |
isdigit() Return True if the string contains only numbers, False otherwise.. |
13 |
islower() Returns True if the string contains at least one case-sensitive character and all of these characters are lowercase, False otherwise |
14 |
isnumeric() Returns True if the string contains only numeric characters, False otherwise |
15 |
isspace() Returns True if the string contains only whitespace, False otherwise. |
16 |
istitle() Returns True if the string is titled (see title()), False otherwise |
17 |
isupper() Returns True if the string contains at least one case-sensitive character and all of these characters are uppercase, False otherwise |
18 |
join(seq) Merges all elements in SEq into a new string, using the specified string as the delimiter |
19 |
len(string) Return string length |
20 |
ljust(width[, fillchar]) Returns a left-aligned string and fills it with fillchar, which defaults to a space, to a new string of length width. |
21 |
lower() Converts all uppercase characters in a string to lowercase. |
22 |
lstrip() Truncate the space or specified character to the left of the string. |
23 |
maketrans() Create a character-mapped transformation table. For the simplest call that takes two parameters, the first parameter is a string representing the character to be converted, and the second parameter is also a string representing the target of the transformation. |
24 |
max(str) Returns the largest letter in the string STR. |
25 |
min(str) Returns the smallest letter in the string STR. |
26 |
replace(old, new [, max]) Replaces str1 in a string with str2, not more than Max times if Max is specified. |
27 |
rfind(str, beg=0,end=len(string)) Similar to find(), but starting from the right. |
28 |
rindex( str, beg=0, end=len(string)) Similar to index(), but starting on the right. |
29 |
rjust(width,[, fillchar]) Return a new string of length width with fillchar(the default space), aligned to the right of the original string |
30 |
rstrip() Delete the space at the end of the string string. |
31 |
split(str=””, num=string.count(str)) Num =string.count(STR)) Uses STR as the delimiter to cut the string. If num has a specified value, only the num+1 substring is cut |
32 |
splitlines([keepends]) Returns a list of rows as elements separated by lines (‘\r’, ‘\r\n’, \n’), with no newlines if keepends is False, and newlines if True. |
33 |
startswith(substr, beg=0,end=len(string)) Checks if the string begins with the specified substring substr, returning True if it does, and False otherwise. If beg and end specify values, check within the specified range. |
34 |
strip([chars]) Execute lstrip() and rstrip() on strings |
35 |
swapcase() Converts uppercase to lowercase and lowercase to uppercase in a string |
36 |
title() Returns a “captioned” string, meaning that all words begin in uppercase and all other letters are lowercase (see istitle()) |
37 |
translate(table, deletechars=””) Convert string characters from the table (256 characters) given by STR, and place the characters to be filtered into the deletechars argument |
38 |
upper() Converts lowercase letters in a string to uppercase letters |
39 |
zfill (width) Returns a string of length width, aligned to the right, preceded by 0 |
40 |
isdecimal() Checks if the string contains only decimal characters, returning true if so, false otherwise. |
Python3 list
Sequences are the most basic data structures in Python. Each element in the sequence is assigned a number – its position, or index, with the first index being 0, the second 1, and so on.
Python has six built-in types for sequences, but the most common are lists and tuples.
The operations that sequences can perform include indexing, slicing, adding, multiplying, and checking members.
In addition, Python has built-in methods for determining the length of a sequence and determining the largest and smallest elements.
Lists, the most common Python data type, can appear as comma-separated values within square brackets.
The data items in the list do not need to be of the same type
Create a list by enclosing the comma-separated data items in square brackets. As follows:
Like string indexes, list indexes start at 0. Lists can be intercepted, combined, and so on.
1. Access the values in the list
Use the subscript index to access the values in the list, and you can also use square brackets to intercept characters, as shown below:
Instance (Python 3.0 +)
#! /usr/bin/python3
list1 = ['Google'.'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])Copy the code
The output of the above example is as follows:
list1[0]: Google
list2[1:5]: [2, 3, 4, 5]Copy the code
2. Update the list
You can modify or update list items, or you can add list items using the append() method, as shown below:
Instance (Python 3.0 +)
#! /usr/bin/python3
list = ['Google'.'Runoob', 1997, 2000]
print ("The third element is:", list[2])
list[2] = 2001
print (The third element after the update is:, list[2])Copy the code
Note: We’ll discuss the use of the append() method in the following sections
The output of the above example is as follows:
The third element is: 1997 and the third element is: 2001Copy the code
3. Delete list elements
You can use the del statement to delete elements of a list, as shown in the following example:
Instance (Python 3.0 +)
#! /usr/bin/python3
list = ['Google'.'Runoob', 1997, 2000]
print ("Original list:", list)
del list[2]
print ("Delete the third element:", list)Copy the code
The output of the above example is as follows:
Original list: ['Google'.'Runoob', 1997, 2000] Delete the third element: ['Google'.'Runoob', 2000]Copy the code
Note: We will discuss the use of the remove() method in the following sections
4. Python list script operators
The list operators for + and * are similar to strings. The + sign is used for composite lists and the * sign is used for duplicate lists.
As follows:
Python expression | The results of | describe |
---|---|---|
len([1, 2, 3]) | 3 | The length of the |
[1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | combination |
[‘Hi!’] * 4 | [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] | repeat |
3 in [1, 2, 3] | True | Whether the element exists in the list |
for x in [1, 2, 3]: print(x, end=” “) | 1 2 3 | The iteration |
Python list interception and concatenation
Python’s list interception and string manipulation types are as follows:
Operation:
Python expression | The results of | describe |
---|---|---|
L[2] | ‘Taobao’ | Read the third element |
L[-2] | ‘Runoob’ | Read the penultimate element from the right: count from the right |
L[1:] | [‘Runoob’, ‘Taobao’] | Outputs all elements starting with the second element |
>>>L=['Google'.'Runoob'.'Taobao']
>>> L[2]
'Taobao'
>>> L[-2]
'Runoob'
>>> L[1:]
['Runoob'.'Taobao'] > > >Copy the code
Lists also support concatenation operations:
>>>squares = [1, 4, 9, 16, 25] >>> squares += [36, 49, 64, 81, 100] >>> squares [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] > > >Copy the code
6. Nested lists
To use nested lists is to create other lists within a list, for example:
>>>a = ['a'.'b'.'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a'.'b'.'c'], [1, 2, 3]]
>>> x[0]
['a'.'b'.'c']
>>> x[0][1]
'b'Copy the code
7. Python list functions & methods
Python contains the following functions:
The serial number | function |
---|---|
1 | len(list) Number of list elements |
2 | max(list) Returns the maximum number of list elements |
3 | min(list) Returns the minimum value of a list element |
4 | list(seq) Converts tuples to lists |
Python contains the following methods:
The serial number | methods |
---|---|
1 | list.append(obj) Add a new object at the end of the list |
2 | list.count(obj) Counts the number of occurrences of an element in a list |
3 | list.extend(seq) Append multiple values from another sequence at the end of the list at once (extending the original list with the new list) |
4 | list.index(obj) Finds the index position of the first match for a value from the list |
5 | list.insert(index, obj) Inserts the object into the list |
6 | list.pop([index=-1]) Removes an element from the list (the last element by default) and returns the value of that element |
7 | list.remove(obj) Removes the first match for a value in the list |
8 | list.reverse() Reverse the elements in the list |
9 | list.sort( key=None, reverse=False) Sort the original list |
10 | list.clear() Empty the list |
11 | list.copy() Copy the list |
Python3 tuple
Python tuples are similar to lists, except that the elements of a tuple cannot be modified.
Tuples use parentheses and lists use square brackets.
Tuple creation is as simple as adding elements in parentheses, separated by commas.
Instance (Python 3.0 +)
>>>tup1 = ('Google'.'Runoob', 1997, 2000);
>>> tup2 = (1, 2, 3, 4, 5 );
>>> tup3 = "a"."b"."c"."d"; # You don't need parentheses
>>> type(tup3)
<class 'tuple'>Copy the code
Create an empty tuple
tup1 = ();Copy the code
When a tuple contains only one element, you need to add a comma after the element, otherwise the parentheses are used as operators:
Instance (Python 3.0 +)
>>>tup1 = (50)
>>> type(tup1) # the type is an integer without a comma
<class 'int'>
>>> tup1 = (50,)
>>> type(tup1) # comma, type tuple
<class 'tuple'>Copy the code
Tuples are similar to strings in that the subscript index starts at 0 and can be truncated, combined, etc.
4. Access the tuple
Tuples can use subscript indexes to access values in tuples, as shown in the following example:
Instance (Python 3.0 +)
#! /usr/bin/python3
tup1 = ('Google'.'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])Copy the code
The output of the above example is as follows:
tup1[0]: Google
tup2[1:5]: (2, 3, 4, 5)Copy the code
5. Modify the tuple
Element values in tuples are not allowed to be modified, but we can concatenate tuples, as in the following example:
Instance (Python 3.0 +)
#! /usr/bin/python3Tup1 = (12, 34.56); tup2 = ('abc'.'xyz')
The following operations to modify a tuple element are illegal.
# tup1[0] = 100
Create a new tuple
tup3 = tup1 + tup2;
print (tup3)Copy the code
The output of the above example is as follows:
(12, 34.56, 'abc'.'xyz')Copy the code
6. Delete the tuple
Element values in tuples are not allowed to be deleted, but we can use the del statement to delete the entire tuple, as shown in the following example:
Instance (Python 3.0 +)
#! /usr/bin/python3
tup = ('Google'.'Runoob', 1997, 2000)
print (tup)
del tup;
print ("Deleted tuple tUP:")
print (tup)Copy the code
After the above instance tuple is deleted, the output variable will have an exception message, and the output is as follows:
Deleted tuple TUP: Traceback (most recent Call last): File"test.py", line 8, in <module>
print (tup)
NameError: name 'tup' is not definedCopy the code
7. Tuple operators
Like strings, tuples can be operated on using + and * signs. This means that they can be combined and copied, generating a new tuple.
Python expression | The results of | describe |
---|---|---|
len((1, 2, 3)) | 3 | Counting elements |
(1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | The connection |
(‘Hi! * 4 ‘) | (‘Hi! ‘, ‘Hi! ‘, ‘Hi! ‘, ‘Hi! ‘) | copy |
3 in (1, 2, 3) | True | Does the element exist |
for x in (1, 2, 3): print (x,) | 1 2 3 | The iteration |
8. Tuple index, interception
Since a tuple is also a sequence, we can access elements in a tuple at a specified position, or we can intercept elements in an index, as follows:
Tuples:
L = ('Google'.'Taobao'.'Runoob')Copy the code
Python expression | The results of | describe |
---|---|---|
L[2] | ‘Runoob’ | Read the third element |
L[-2] | ‘Taobao’ | Reverse reading; Read the penultimate element |
L[1:] | (‘Taobao’, ‘Runoob’) | Intercepts elements, all elements starting from the second. |
The running example is as follows:
>>> L = ('Google'.'Taobao'.'Runoob')
>>> L[2]
'Runoob'
>>> L[-2]
'Taobao'
>>> L[1:]
('Taobao'.'Runoob')Copy the code
9. Tuple built-in functions
The Python tuple contains the following built-in functions
The serial number | Methods and Description | The instance |
---|---|---|
1 | len(tuple) Count the number of tuple elements. |
|
2 | max(tuple) Returns the maximum number of elements in a tuple. |
|
3 | min(tuple) Returns the minimum value of an element in a tuple. |
|
4 | tuple(seq) Convert lists to tuples. |
|
Python3 dictionary
Dictionaries are another mutable container model that can store objects of any type.
Each key=>value pair of the dictionary is separated by a colon (:), and each pair is separated by a comma (,). The entire dictionary is enclosed in curly braces ({}) in the following format:
d = {key1 : value1, key2 : value2 }Copy the code
Keys must be unique, but values do not.
Values can take any data type, but keys must be immutable, such as strings, numbers, or tuples.
A simple dictionary example:
dict = {'Alice': '2341'.'Beth': '9102'.'Cecil': '3258'}Copy the code
You can also create a dictionary like this:
dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6:37}Copy the code
1. Access the values in the dictionary
Place the corresponding key in square brackets, as shown in the following example:
The instance
#! /usr/bin/python3
dict = {'Name': 'Runoob'.'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])Copy the code
The output of the above example is as follows:
dict['Name']: Runoob
dict['Age'] :Copy the code
If you access data with a key that is not in the dictionary, you will get the following error:
The instance
#! /usr/bin/python3
dict = {'Name': 'Runoob'.'Age': 7, 'Class': 'First'}
print ("dict['Alice']: ", dict['Alice'])Copy the code
The output of the above example is as follows:
Traceback (most recent call last):
File "test.py", line 5, in <module>
print ("dict['Alice']: ", dict['Alice'])
KeyError: 'Alice'Copy the code
2. Modify the dictionary
To add new content to a dictionary, add new key/value pairs. For example, modify or delete existing key/value pairs:
The instance
#! /usr/bin/python3
dict = {'Name': 'Runoob'.'Age': 7, 'Class': 'First'}
dict['Age'] = 8 # update Age
dict['School'] = "Rookie Tutorial" # Add information
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])Copy the code
The output of the above example is as follows:
dict['Age']: 8
dict['School'[: Rookie tutorialCopy the code
3. Delete the dictionary element
You can delete a single element or you can empty the dictionary in a single operation.
Example shows deleting a dictionary with the del command as follows:
The instance
#! /usr/bin/python3
dict = {'Name': 'Runoob'.'Age': 7, 'Class': 'First'}
del dict['Name'] # delete key 'Name'
dict.clear() # Empty the dictionary
del dict # delete dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])Copy the code
But this raises an exception because the dictionary no longer exists after the del operation:
Traceback (most recent call last):
File "test.py", line 9, in <module>
print ("dict['Age']: ", dict['Age'])
TypeError: 'type' object is not subscriptableCopy the code
Note: The del() method is also discussed later.
4. Dictionary key features
Dictionary values can be any Python object, either standard or user-defined, but not keys.
Two important points to remember:
1) The same key is not allowed to appear twice. If the same key is assigned twice, the last value will be remembered, as in the following example:
The instance
#! /usr/bin/python3
dict = {'Name': 'Runoob'.'Age': 7, 'Name': 'Rookie'}
print ("dict['Name']: ", dict['Name'])Copy the code
The output of the above example is as follows:
dict['Name'] : a rookieCopy the code
2) Keys must be immutable, so you can use numbers, strings, or tuples instead of lists, as in the following example:
The instance
#! /usr/bin/python3
dict = {['Name'] :'Runoob'.'Age'7} :print ("dict['Name']: ", dict['Name'])Copy the code
The output of the above example is as follows:
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name'] :'Runoob'.'Age': 7}
TypeError: unhashable type: 'list'Copy the code
5. Dictionary built-in functions & methods
The Python dictionary contains the following built-in functions:
The serial number | Function and Description | The instance |
---|---|---|
1 | len(dict) Count the number of dictionary elements, the total number of keys. |
|
2 | str(dict) Output dictionaries, represented as printable strings. |
|
3 | type(variable) Returns the input variable type, or dictionary type if the variable is a dictionary. |
|
The Python dictionary contains the following built-in methods:
The serial number | Function and Description |
---|---|
1 | radiansdict.clear() Delete all elements from the dictionary |
2 | radiansdict.copy() Returns a shallow copy of the dictionary |
3 | radiansdict.fromkeys() Create a new dictionary with the elements in the sequence seq as the dictionary keys and val as the initial values for all the keys in the dictionary |
4 | radiansdict.get(key, default=None) Returns the value of the specified key, or default if the value is not in the dictionary |
5 | key in dict Returns true if the key is in the dict, false otherwise |
6 | radiansdict.items() Returns a traversable array of tuples as a list |
7 | radiansdict.keys() Returns an iterator that can be converted to a list using list() |
8 | radiansdict.setdefault(key, default=None) Similar to get(), but if the key does not exist in the dictionary, the key is added and the value is set to default |
9 | radiansdict.update(dict2) Update the key/value pair of dictionary dict2 to the dict |
10 | radiansdict.values() Returns an iterator that can be converted to a list using list() |
11 | pop(key[,default]) Deletes the value corresponding to the given dictionary key, returning the deleted value. The key value must be given. Otherwise, the default value is returned. |
12 | popitem() Randomly returns and deletes the last pair of keys and values in the dictionary. |
Python3 collection
A set is an unordered sequence of non-repeating elements.
You can use curly braces {} or the set() function to create a collection. Note: To create an empty collection, you must use set() instead of {}, because {} is used to create an empty dictionary.
Create format:
parame = {value01,value02,... } orset(value)Copy the code
Instance (Python 3.0 +)
>>>basket = {'apple'.'orange'.'apple'.'pear'.'orange'.'banana'} > > >print(basket) # This is a demonstration of the de-duplication function
{'orange'.'banana'.'pear'.'apple'} > > >'orange' in basket Quickly determine if the element is in the collection
True
>>> 'crabgrass' in basket
False
>>> # Below shows the operation between two sets.. >>> a =set('abracadabra')
>>> b = set('alacazam')
>>> a
{'a'.'r'.'b'.'c'.'d'}
>>> a - b Elements contained in set A that are not contained in set B
{'r'.'d'.'b'}
>>> a | b All elements contained in the set A or B
{'a'.'c'.'r'.'d'.'b'.'m'.'z'.'l'}
>>> a & b The elements contained in both sets A and b
{'a'.'c'}
>>> a ^ b # Elements not contained in both a and B
{'r'.'d'.'b'.'m'.'z'.'l'}Copy the code
Similar to list inference, Set comprehension is supported for the same Set:
Instance (Python 3.0 +)
>>>a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r'.'d'}Copy the code
The basic operations of collections
1. Add elements
The syntax is as follows:
s.add( x )Copy the code
Element X is added to collection S, and nothing is done if the element already exists.
Instance (Python 3.0 +)
>>>thisset = set(("Google"."Runoob"."Taobao"))
>>> thisset.add("Facebook") > > >print(thisset)
{'Taobao'.'Facebook'.'Google'.'Runoob'}Copy the code
There is also a method that can add elements, and the arguments can be lists, tuples, dictionaries, etc. The syntax is as follows:
s.update( x )Copy the code
You can have multiple x’s, separated by commas.
Instance (Python 3.0 +)
>>>thisset = set(("Google"."Runoob"."Taobao")) > > > thisset. Update ({1, 3}) > > >print(thisset)
{1, 3, 'Google'.'Taobao'.'Runoob'} > > > thisset. Update ([1, 4], [5, 6]) > > >print(thisset)
{1, 3, 4, 5, 6, 'Google'.'Taobao'.'Runoob'} > > >Copy the code
2. Remove elements
The syntax is as follows:
s.remove( x )Copy the code
Removes element X from collection S, and an error occurs if the element does not exist.
Instance (Python 3.0 +)
>>>thisset = set(("Google"."Runoob"."Taobao"))
>>> thisset.remove("Taobao") > > >print(thisset)
{'Google'.'Runoob'}
>>> thisset.remove("Facebook") # There is no error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Facebook'
>>>Copy the code
There is also a way to remove an element from the collection, and no error occurs if the element does not exist. The format is as follows:
s.discard( x )Copy the code
Instance (Python 3.0 +)
>>>thisset = set(("Google"."Runoob"."Taobao"))
>>> thisset.discard("Facebook") # There is no error
>>> print(thisset)
{'Taobao'.'Google'.'Runoob'}Copy the code
We can also set random deletion of an element in the collection in the following syntax:
s.pop() Copy the code
Script Pattern instance (Python 3.0+)
Output result:
$ python3 test.py
RunoobCopy the code
The test results vary from time to time.
In interactive mode, however, POP is the first element of the deleted collection (the first element of the sorted collection).
Instance (Python 3.0 +)
>>>thisset = set(("Google"."Runoob"."Taobao"."Facebook"))
>>> thisset.pop()
'Facebook'
>>> print(thisset)
{'Google'.'Taobao'.'Runoob'} > > >Copy the code
3. Calculate the number of set elements
The syntax is as follows:
len(s)Copy the code
Calculate the number of elements of set S.
Instance (Python 3.0 +)
>>>thisset = set(("Google"."Runoob"."Taobao"))
>>> len(thisset)
3Copy the code
4. Empty the collection
The syntax is as follows:
s.clear()Copy the code
Empty set S.
Instance (Python 3.0 +)
>>>thisset = set(("Google"."Runoob"."Taobao"))
>>> thisset.clear()
>>> print(thisset)
set(a)Copy the code
5. Determine if the element exists in the collection
The syntax is as follows:
x in sCopy the code
Check whether element x is in set S, return True if it exists, False if it does not.
Instance (Python 3.0 +)
>>>thisset = set(("Google"."Runoob"."Taobao")) > > >"Runoob" in thisset
True
>>> "Facebook" in thisset
False
>>>Copy the code
6. Collect a complete list of built-in methods
methods | describe |
---|---|
add() | Add elements to the collection |
clear() | Removes all elements from the collection |
copy() | Copy a collection |
difference() | Returns the difference set of multiple collections |
difference_update() | Removes an element from the collection that also exists in the specified collection. |
discard() | Deletes the specified element from the collection |
intersection() | Returns the intersection of collections |
intersection_update() | Returns the intersection of collections. |
isdisjoint() | Checks whether two collections contain the same element, returning True if none, False otherwise. |
issubset() | Determines whether the specified collection is a subset of the method parameter collection. |
issuperset() | Determines whether the method’s set of parameters is a subset of the specified set |
pop() | Randomly remove elements |
remove() | Remove the specified element |
symmetric_difference() | Returns a collection of non-repeating elements in two collections. |
symmetric_difference_update() | Removes an element from the current collection that is identical to another specified collection and inserts a different element from another specified collection into the current collection. |
union() | Returns the union of two collections |
update() | Add elements to the collection |