Python Programming quick start 01

Introduction to Python Programming (Day01)

The whole series has six days and twelve chapters. Only basic introduction to final exam

Chapter 1 overview of Python language

1. The origin of Python

  • Python by Netherlandsmathematics and computer science [Guido van Rossum] of the Research Society( https://baike.baidu.com/item/Guido Van Rossum / 3225314) was designed in the early 1990s as a door called ABC language A substitute for. Python provides efficient advanced data structure , but also simple and effective object-oriented Programming.
  • Python was founded by the Dutch Guido van Rossum (Guido van Rossum). During Christmas 1989, in Amsterdam Guido, to kill Christmas Boring, determined to develop a new script interpreter as ABC language An inheritance of.
  • Python 2 was released on October 16, 2000. The stable version is Python 2.7. Python 3 was released on December 3, 2008 and is not fully compatible with Python 2.
  • Differences between 2.x and 3.x versions:
    • Print function: there is no print statement in python2. Instead, the print() function in python3 is used. That is, the objects to be output must be enclosed in parentheses in Python 3.
    • Use__ future__ Module: Python 3.x introduces some keywords and features that are incompatible with Python 2.x. In Python 2.x, you can use the built-in__ future__ The module imports these new contents. If you want the code written in Python 2.x environment to run in Python 3.x, it is recommended to use__ future__ modular.
    • Integer division: in python 2.x, the result of integer division is an integer. The decimal part is completely ignored. The floating-point division will retain the decimal part to get a floating-point result. In python 3.x, for the division between integers, the result will also be a floating point number.
    • Unicode: Python 2 has ASCII based str() type, which can be converted to unicode type through unicode() function, but there is no byte type. In Python 3.
    • Trigger exception: Python 2 supports both old and new exception trigger syntax, but Python 3 only supports parenthesized syntax, otherwise SyntaxError will be triggered.
    • Xrang: in Python 2.x, you often create an iterative object with xrange (), usually in the for loop or list, collection, dictionary derivation. In Python 3, the implementation of range() is the same as that of xrange() function, so there is no dedicated xrange() (using xrange() in Python 3 will trigger NameError).
  • Python Tiobe Leaderboard:

2.Python language features

  • Python is a simple, cross platform, open source, free interpretive * *, process oriented and object-oriented, extensible, embeddable * * high-level programming language with rich and powerful libraries.
  • Python supports both imperative and functional programming.
  • Python is often nicknamed glue language, which can easily connect various modules made in other languages (especially C/C + +).
  • Python applications:

3.python interpreter

  • Directly obtained an official version of the interpreter: CPython. This interpreter is developed in C language, so it is called CPython. Running python on the command line starts the CPython interpreter.

  • CPython uses > > > as the prompt.

  • There are other interpreters:

    • Jython is a Python interpreter running on the Java platform;
    • IronPython is a Python interpreter running on Microsoft. Net platform;
    • PyPy is another Python interpreter.

4. Download and install Python software

  1. open python official website , download the corresponding version:

  1. Run the installation program;

  • Open the CMD command line and enter python, as shown in the figure below, it is successful.

  • Exit the above python running environment and enter exit().

If Add Python 3.9 to PATH is not checked at the beginning of installation, the following will appear when running in cmd command line:

  • There are two solutions to the above problems:
    • Reinstall python software and check it when reinstalling;
    • Manually configure the python environment:
  1. Right click the computer, select properties, select the Advanced tab, and click environment variables;

  1. Add personal python installation path and configure path environment;

  1. In cmd, run python.

At this point, the python installation configuration is complete.

View Python software version

1,Enter in the command window python Or enter python -V
>python -V
Python 3.9.7

2,stay python Input in interactive mode
>python
>>>help()

3,stay python The following operations are performed in the interactive mode of:
>>> import sys
>>> sys.version

4,stay python The following operations are performed in the interactive mode of:
>>> import sys
>>> sys.version_info
        
5,stay python The following operations are performed in the interactive mode of:
>>> import sys
>>> sys.winver
        
6,stay python The following operations are performed in the interactive mode of:
>>> import platform
>>> platform.python_version()

5. Write and run python

Default programming environment: IDLE

Other common development environments:

  • Anaconda3
  • PyCharm
  • VS Code
  • Eclipse+PyDev
  • wingIDE
  • Eric

1. Write code with a text editor

  • In Python, you need to select an appropriate text editor to write Python code, such as Notepad, Notepad + + and other text editors. Here is a python script written with Notepad + + and run in cmd.
  • After opening Notepad + +, create a new file, then write the code to the file and save it.

  • For the newly created file, set the language corresponding to the code and highlight the implementation syntax: language ⇒ P ⇒ Python.

  • Open cmd, switch to the directory where the corresponding Python script file is located, and enter the full file name just created to run the script.

2. Write code in Python shell in command line format

  • In IDLE, if the interactive programming mode is used, enter the corresponding command directly behind the prompt "> > >" and press enter for execution. If the execution is successful, you can see the execution result immediately, otherwise an exception will be thrown.

3. Write code with Python Shell with graphical interface

When you need to write a large number of lines of Python code, you need to write programs (also known as scripts) to avoid cumbersome.

  • Steps to write and run programs in IDLE:

    • (1) Start IDLE;

    • (2) Select the menu file > new file to create a program file, enter the code and save it as a file with the extension. py.

  • (3) Select the menu run > Run module F5 to run the program, and the program running results will be directly displayed on the IDLE interactive interface.

In some cases, you may need to run Python program files in a command prompt environment. Press and hold Win+R at the same time, enter CMD, and then execute the python program.

If HelloWorld.py is not under the current path, you need to write the path name in front, such as F:\Python\Work\Hello.py

  • Some commonly used shortcut keys in IDLE are shown in the following table:
Add indentCtrl+]
Reduction advanceCtrl+[
add comments of explanationsAlt+3
To commentAlt+4
Previous commandAlt+p
Next commandAlt+n
EnterCopy after mouse selection

6.Python comments

  • Python single line comment
    • Pound sign (#) is often used as a single line comment symbol. When # is used in code, any data on its right will be ignored during program execution and regarded as comments.
>>> print('Hello world.')  # Output Hello world
Hello world.
  • Python multiline comment
    • In Python, when a comment has multiple lines, you need a multi line annotator to annotate multiple lines. A multiline comment encloses the comment with three single quotation marks' 'or three double quotation marks'', for example:
'''
This is a multiline comment with three single quotes
 This is a multiline comment with three single quotes 
This is a multiline comment with three single quotes
'''
print("Hello, World!")

Chapter 2 fundamentals of Python language

1. Variables in Python

  • The value of the variable stored in memory, which means that a space will be opened up in memory when the variable is created.

  • Based on the data type of the variable, the interpreter allocates the specified memory and determines what data can be stored in memory.

  • Therefore, variables can specify different data types. These variables can store integers, decimals or characters.

1. Variable assignment

  • Variable assignment in Python does not require a type declaration.
  • Each variable is created in memory, including the identification, name and data of the variable.
  • Each variable must be assigned before use, and the variable will not be created until it is assigned.
  • The equal sign = is used to assign values to variables.
  • To the left of the equal sign = operator is a variable name, and to the right of the equal sign = operator is the value stored in the variable. For example:
counter = 100 # Assign integer variable
miles = 1000.0 # float 
name = "subei" # character string
 
print(counter)
print(miles)
print(name)

2. Precautions for variables

When defining variable names, you should pay attention to the following issues:

  • Variable names must begin with letters, Chinese characters, or underscores, but variables that begin with an underscore have special meanings in Python; the details are as follows:

    1. Single leading underscore: the meaning of the underscore prefix is to inform other programmers that variables or methods starting with a single underscore are for internal use only.
    2. Single end underscore: a single end underscore (suffix) is a convention to avoid naming conflicts with Python keywords.
    3. Double leading underscore _: the double underscore prefix will cause the Python interpreter to rewrite the attribute name to avoid naming conflicts (name decoration) in subclasses and become the format of "class name _ variable name".
    4. Double leading and double trailing underscores _: if a name starts and ends with double underscores at the same time, name modifiers are not applied. Variables surrounded by double underlined prefixes and suffixes are not modified by the Python interpreter.
    5. Single underscore: a single independent underscore is used as a name to indicate that a variable is temporary or irrelevant. In interactive mode, it also indicates the value of the most recent expression (success).
  • Variable names cannot contain spaces and punctuation marks (parentheses, quotation marks, commas, slashes, backslashes, colons, periods, question marks, etc.);

  • Keywords cannot be used as variable names. After importing the keyword module, use print(keyword.kwlist) to view all Python keywords;

    >>> import keyword
    >>> print(keyword.kwlist)
    

  • It is not recommended to use the built-in module name, type name or function name, imported module name and its member name as variable names, which will change its type and meaning. You can view all built-in modules, types and functions through dir(builtins);

    • Note: the dir() function returns the list of variables, methods and defined types in the current range without parameters; with parameters, it returns the list of properties and methods of parameters.
  • Variable names are sensitive to the case of English letters. For example, student and student are different variables.

3. Keywords in Python

keyworddescribe
andLogical operators.
asCreate an alias.
assertFor debugging.
breakJump out of the loop.
classDefine classes.
continueContinue to the next iteration of the loop.
defDefine functions.
delDelete object.
elifUsed in conditional statements, equivalent to else if.
elseUsed for conditional statements.
exceptHandle exceptions and how to execute when exceptions occur.
FalseBoolean value to compare the results of the operation.
finallyHandling exceptions, whether or not there are exceptions, will execute a piece of code.
forCreate a for loop.
fromImport specific parts of the module.
globalDeclare global variables.
ifWrite a conditional statement.
importImport module.
inCheck whether a value exists in a list, tuple, etc.
isTest whether the two variables are equal.
lambdaCreate anonymous functions.
NoneRepresents a null value.
nonlocalDeclare nonlocal variables.
notLogical operators.
orLogical operators.
passnull statement, a statement that does nothing.
raiseAn exception occurred.
returnExit the function and return a value.
TrueBoolean value to compare the results of the operation.
tryWrite a try... except statement.
whileCreate a while loop.
withUsed to simplify exception handling.
yieldEnd the function and return to the generator.

4.Python code specification

  1. indent

    1. Class definition, function definition, selection structure, loop structure and with block. The colon at the end of the line indicates the beginning of indentation.
    2. python programs rely on the indentation of code blocks to reflect the logical relationship between codes. The end of indentation means the end of a code block.
    3. Code blocks at the same level must be indented the same amount.
    4. Generally speaking, the basic indent unit is 4 spaces.
  2. notes

    1. Starting with # indicates that the content after # of this line is a comment.
    2. Content contained between a pair of three quotation marks'... '' or '...' 'and not belonging to any statement will be considered as comments by the interpreter.
  3. Each import statement imports only one module, preferably in the order of standard library, extension library and user-defined library.

    import csv
    import random
    import pands
    
  4. If a line statement is too long, you can add a continuation character \ at the end of the line to break the line into multiple lines, but it is more recommended to use parentheses to contain multiple lines.

  1. Necessary spaces and blank lines

    1. It is recommended to add a space on both sides of the operator and after the comma.
    2. It is recommended to add an empty line between code blocks of different functions and between function definitions to increase readability.
  2. You can use pip to install the pep8 tool, and then use the command pep8 test.py to check the normalization of Python code in the test.py file. The commonly used optional parameters of pep8 are – show source, – first, – show-pep8, and so on.

  1. Flake8 combines the characteristics of pyflakes and pep8. You can check more contents. It is recommended to use it first. You can install flake8 directly by using PIP install, and then use the command flake8 test.py to check the standardization of the code in test.py.

  2. You can also use pip to install pylint, and then use the command-line tool pylint or the visualization tool pylint GUI to check the normalization of the program.

After installing Python 3, there is no solution to the Scripts directory

  • After setting the python environment variable, cmd executes the command: python -m ensurepip.
  • Then add the F:\Python\python3.9.7\Scripts directory in the PATH.

5.Python file name

  • . py: Python source file, interpreted and executed by Python interpreter.
  • . pyw: Python source file, commonly used for graphical interface program files.
  • . pyc: Python bytecode file. You cannot directly view the contents of this type of file with a text editor. It can be used to hide Python source code and improve running speed. For Python modules, they will be compiled into bytecode when imported for the first time, and the ". pyc" file will be preferentially used when imported again in the future to improve the loading and running speed of the module. For non module files, the ". pyc" file is not generated during direct execution, but py can be used_ The compile() function of the compile module is compiled to improve loading and running speed. In addition, python also provides the compileall module, which contains compile_dir(),compile_file() and compile_path() and other methods are used to support the compilation of batch Python source program files.
  • . pyo: optimized python bytecode file. Similarly, its contents cannot be viewed directly with a text editor. You can use "python – O -m py_compile file.py" or "python – OO -m py_compile file.py" for optimized compilation. Python 3.5 no longer supports. pyo files.
  • . pyd: it is generally a binary file written and compiled by other languages. It is often used to implement python programming interface plug-ins or Python dynamic link libraries of some software tools.

2. Objects in Python

1. Objects and references in Python

  • The object in Python is a memory block with a specific interaction interface after wrapping data and functions in programming.
  • Object is the most basic concept in python language. Everything handled in python is an object. There are many built-in objects in python for programmers to use. The built-in objects can be used directly, such as numbers, strings, lists, del, etc; Non built-in objects can only be used by importing modules, such as sine function sin(x), random number generation function random().
    • Note: built in objects can be viewed using dir(builtins).
  • Each object has three properties:
    • Identity is the address of the object in memory;
    • Type is used to represent the data type (class) to which the object belongs. The type of object determines what type of value the object can store, what attributes and methods it has, and what operations it can perform;
    • Value, the data represented by the object.
>>> a=123    # 123 creates an int (integer) object and represents it with a
>>> id(a)    
2921335118000	# Identity is represented by such a string of numbers
>>> type(a)		# View the type of a
<class 'int'>
>>> a		# Displays the value represented by a
123
>>>
>>> b=6
>>>

In short, the above code performs the following operations:
(1)Use variables b To represent object 6. In order to use an object, you must use an assignment operation“="Assign an object to a variable (also known as binding an object to a variable), so that the data in the memory data block can be manipulated through the variable.
(2)If variable b Does not exist, create a new variable b. 
(3)Will variable b Connect with the number 6, i.e. variable b As a reference to object 6, the variable can be regarded as a pointer to the memory space of the object.
  • When multiple variables refer to the same object, it is called shared reference.
>>> a=1
>>> b=a		# b becomes a reference to 1
>>> a=2		# A becomes a reference to object 2
>>> print(b)
1		# Since a variable is only a reference to an object, changing the reference of a does not result in the change of b
>>>
  • In Python, multiple variables are allowed to point to the same value, for example:

>>> x=3
>>> id(x)
2921334925680
>>> y=x
>>> id(y)
2921334925680
>>>
  • However, after modifying the value of one variable, its memory address will change, but this will not affect the other variable. For example, the above code will continue to execute the following code:

>>> x += 6
>>> id(x)
2921334925872
>>> y
3
>>> id(y)
2921334925680
>>>
>>> x='python'
>>>

# The above code creates a variable x, which is a reference to the string object 'Python', that is, the value of the object pointed to by the variable x is' Python '.

Note: the type belongs to the object, the variable has no type, and the variable is only the reference of the object. The so-called variable type refers to the type of the object referenced by the variable. The type of the variable changes with the change of the assigned type.

2. Use of is and = = in Python

  • ==It is a comparison operator in the python standard operator. It is used to compare and judge whether the values of two objects are equal. It is to compare whether the contents of two objects are equal, that is, whether the "values" of two objects are equal, regardless of whether their reference addresses in memory are the same.
>>> a=[3,4,5]
>>> b=[3,4,5]
>>> id(a)
2921340292352
>>> id(b)
2921340330368
>>> a==b
True
>>>
  • Is compares whether two instance objects are identical, whether they are the same object, and whether the memory addresses occupied are the same. That is, is compares two conditions:
    1. Same content.
    2. Same address in memory.
>>> a=[4,5,6]
>>> b=[4,5,6]
>>> id(a)
2921340330624
>>> id(b)
2921340292352
>>> a is b
False
>>>
>>> a=[5,6,7]
>>> b=a
>>> id(a)
2921340330368
>>> id(b)
2921340330368
>>> a is b
True
>>>
  • Python adopts value based memory management. If different variables are assigned the same value, only one copy of this value is saved in memory, and multiple variables point to the first address of memory space with the same value, which can reduce the occupation of memory space and improve memory utilization.
  • When Python starts, it caches integers in the [- 5, 256] interval. That is, if the values of multiple variables are equal and within the [- 5, 256] interval, these variables share the memory space of the same value.
  • For integers outside the interval [- 5, 256], variables with the same value and different names in the same statement in the same program or interaction mode will share the same memory space. Different programs or different statements in interaction mode do not abide by this Convention.
>>> x=-6
>>> y=-6
>>> id(x)==id(y)
False
>>> x=-5
>>> y=-5
>>> id(x)==id(y)
True
>>> x=255
>>> y=255
>>> id(x)==id(y)
True
>>> x=256
>>> y=256
>>> id(x)==id(y)
True
>>> x=257
>>> y=257
>>> id(x)==id(y)
False
>>>
>>> x=4.0
>>> y=4.0
>>> id(x)==id(y)
False
>>> x,y=2000,2000
>>> id(x)==id(y)
True
>>> x=[252525,252525]
>>> y=[252525,252525]
>>> id(x[0])==id(x[1])
True
>>> id(y[0])==id(y[1])
True
>>> id(x[0])==id(y[0])
False
>>>

  • Through the above figure: Python does not cache real numbers. Variables with the same value and different names in interactive mode (not in the same statement) do not share the same memory space. Variables with the same value and different names in the same program will share the same memory space.

The execution process of assignment statement is: first calculate the value of the expression on the right side of the equal sign, then find a location in memory to store the value, and finally create a variable and point to the memory address. Variables in Python do not directly store the value, but store the memory address or reference of the value, which is also the reason why the variable type can be changed at any time.

  • Use the sys.getrefcount() function to view the number of references.
    • python is full of objects and variables are references to objects, which is a bit like C language pointers.
    • The sys module actually refers to the python system. The sys.getrefcount interface can query the reference count of objects.
    • When using the sys.getrefcount() function, the function will be referenced once,
    • When using parameter reference, the parameter will be referenced once, and a temporary reference will be generated automatically, so the number of references will be 1 more than expected.
>>> import sys
>>> a=1
>>> sys.getrefcount(a)
86
>>> b=a
>>> sys.getrefcount(b)
87
>>> sys.getrefcount(a)
87
>>> c=[1,2,3]
>>> sys.getrefcount(c)
2
>>> d=c
>>> sys.getrefcount(d)
3
>>> sys.getrefcount(c)
3
>>> del d	# The del statement decreases the reference count
>>> sys.getrefcount(c)
2
>>>

3. Data type

  • In Python language, all objects have a data type. Python data type is defined as a set of values and a set of operations defined on the value set. An object can be executed and only the operations defined by its corresponding data type are allowed to be executed.
  • There are six standard data types in Python:
    • Number (int integer, float floating point, bool Boolean, complex complex) can represent a number of any size.
    • String (string)
    • list
    • Tuple (tuple)
    • dictionary
    • set

1.int integer

  • Integer types in Python can be divided into:

    Decimal integer, such as 0-1,9,123
    
    Hexadecimal integer, requiring 16 digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 a,b,c,d,e,f To represent an integer, it must be expressed as 0 x Start, such as 0 x10,0xfa,0xabcdef       
    Note: a,b,c,d,e,f It can be uppercase or lowercase
    
    Octal integer. It only needs 8 digits 0, 1, 2, 3, 4, 5, 6 and 7 to represent the integer. It must be 0 o Start, such as 0 o35,0o11
    
    Binary integer. Only two numbers 0 and 1 are required to represent the integer, which must be expressed as 0 b Start with, for example, 0 b101,0b100
    
  • Binary conversion:

Decimal conversion to other decimal numbers: bin(),oct(),hex()  
>>> bin(20)
'0b10100'
>>> oct(20)
'0o24'
>>> hex(200)
'0xc8'
>>>

Convert other decimal numbers to decimal:
	a.The original data is a string, which can be used int("Other hexadecimal numbers", base=). 
    	Note: other hexadecimal numbers may or may not be marked         
        >>> int("637270012", base=8)
        108883978
        >>> int("0o637270012", base=8)
        108883978
        >>>

	b.The original data is a string, and the hexadecimal number is preceded by a flag, such as 0 before binary b,have access to eval()
    	>>> x=eval('0b1010')
        >>> x
        10
        >>>
        
	c.Add a flag before the binary number, such as 0 before the binary number b,It is automatically converted to decimal when displayed.  
    	>>> 0b1010
        10
        >>>
Binaryoctal number systemdecimal systemhexadecimal
Binary-bin(int(x,8))bin(int(x,10))bin(int(x,16))
octal number systemoct(int(x,2))-oct(int(x,10))oct(int(x,16))
decimal systemint(x,2)int(x,8)-int(x,16)
hexadecimalhex(int(x,2))hex(int(x,8))hex(int(x,10))-

2.float float

  • Floating point numbers are also called decimals (some floating point numbers cannot be accurately stored in the computer).
1,General writing
   15.0,0.37,-11.2,1.2e2,314.15e-2
2,Special writing
   .3  ,12.
3,Special string
    A,"Infinity"or"inf","-Infinity"or"-inf",Can use float()Convert to infinity
    >>> x=float("inf")
    >>> x
    inf
    >>> x=float("Infinity")
    >>> x
    inf
    >>> x=float("Infinity")
    >>> y=float("inf")
    >>> x==y
    True
    >>>

    B,"nan",representative Not A Number(Not a number), it is not equal to 0.
    >>> x=float("nan")
    >>> x
    nan
    >>> y=float("nan")
    >>> y
    nan
    >>> x==y
    False
    >>>
    
Note: two infinite numbers are equal, and two are not numbers"nan"The comparison is not equal.    
  • The number of significant digits of a floating-point number is 17.
>>> 123456789012345678.0+1-123456789012345678.0
0.0
>>> 123456789012345678.0-123456789012345678.0+1
1.0
>>>

3.bool Boolean

  • bool Boolean. bool Boolean corresponds to two Boolean values: True and False, corresponding to 1 and 0 respectively.
>>> True+1
2
>>> False-1
-1
>>>

4.complex complex

  • Python has built-in support for complex types.
>>> a=3+4j
>>> b=5+6j
>>> c=9-8j
>>> d=a+b+c
>>> d
(17+2j)
>>> d.real		# View complex real part
17.0
>>> d.imag		# View imaginary part of complex number
2.0
>>> c.conjugate()	# Returns the conjugate complex number
(9+8j)
>>> a*b			# Complex multiplication
(-9+38j)
>>> b/c			# Complex division
(-0.020689655172413775+0.6482758620689656j)
>>>

Note:
	1.The so-called conjugation can be understood as the transformation of plus and minus signs. The multiplication of two complex numbers conjugated to each other is a real constant.
	2.The addition of complex numbers shall be carried out according to the following rules: z1=a+bi,z2=c+di Is any two complex numbers, then their sum is (a+bi)+(c+di)=(a+c)+(b+d)i. 
    3.The subtraction of complex numbers shall be carried out according to the following rules: z1=a+bi,z2=c+di Is any two complex numbers, then their difference is (a+bi)-(c+di)=(a-c)+(b-d)i. 
    4.The multiplication of complex numbers shall be carried out according to the following rules: z1=a+bi,z2=c+di(a,b,c,d∈R)Is any two complex numbers, then their product(a+bi)(c+di)=(ac-bd)+(bc+ad)i. 
    5.The division of complex numbers shall be carried out according to the following rules: the division can be converted into multiplication, and the numerator and denominator are multiplied by the conjugate of denominator at the same time.
    	set up(a+bi)/(c+di),First multiply both the numerator and denominator(c-di),This is(c+di)Conjugate complex of.
        So the denominator becomes constant(a+bi)/(c+di)
					=(a+bi)*(c-di)/(c+di)*(c-di)
					=(ac+adi+bci+bd)/(c*c+d*d)

Note: Python 3.6.x began to support using a single underscore as a separator in the middle of numbers to improve the readability of numbers, which is similar to mathematically using a comma as a thousand separator.

>>> 1_000_000
1000000
>>> 2_4_2_6
2426
>>> 1_2 + 6_1j
(12+61j)
>>> 1_2.5_6_1
12.561
>>>

5. Calculation of numerical data

  • The numeric data of Python supports +, -, *, / / /, * *,% (complex numbers are not supported).
>>> 25/5
5.0
>>> 18//4
4
>>> 18//4.
4.0
>>> 18//-3
-6
>>> 18//-4
-5
>>> 2.1**3
9.261000000000001
>>> 18//-3.
-6.0
>>> 18%5
3
>>> 18%5.0
3.0
>>> 18%(3+4j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't mod complex numbers.
>>> (3+4j)**3
(-117+44j)
>>>

Mathematical functions commonly used in numerical types

functionReturn value (description)
abs(x)Returns the absolute value of a number. For example, abs(-10) returns 10
math.ceil(x)Returns the up integer of a number. For example, math.ceil(4.1) returns 5
cmp(x, y)Returns - 1 if x < y, 0 if x == y, and 1 if x > y
exp(x)Returns the x-Power of e (ex). For example, math.exp(1) returns 2.718281828459045
fabs(x)Returns the absolute value of a number. For example, math.fabs(-10) returns 10.0
math.floor(x)Returns the rounded down integer of a number. For example, math.floor(4.9) returns 4
math.log(x)For example, math.log(math.e) returns 1.0, and math.log (100,10) returns 2.0
math.log10(x)Returns the logarithm of x based on 10. For example, math.log10(100) returns 2.0
max(x1, x2,...)Returns the maximum value of a given parameter, which can be a sequence.
min(x1, x2,...)Returns the minimum value of a given parameter, which can be a sequence.
math.modf(x)Returns the integer part and decimal part of x. The numerical symbols of the two parts are the same as x. the integer part is represented by floating point.
pow(x, y)The value after x**y operation.
round(x [,n])Returns the rounded value of floating-point number x. if n is given, it represents the number of digits rounded to the decimal point.
sqrt(x)Returns the square root of the number x
  • isinstance() function
>>> a=2
>>> isinstance(a,int)
True
>>> isinstance(a,str)
False
>>> isinstance(a,(str,int,list))	# Is one of the tuples that returns True
True
>>>
  • Note: the difference between isinstance() and type():
    • 1) type() does not consider a subclass as a parent type and does not consider inheritance.
    • 2) isinstance() will consider the subclass as a parent type and consider the inheritance relationship.

6.del statement

>>> a=1		# Object 1 is referenced by variable a, and the reference counter of object 1 is 1  
>>> b=a		# Object 1 is referenced by variable b, and the reference counter of object 1 is incremented by 1 
>>> c=a		# 1 object 1 is referenced by variable c, and the reference counter of object 1 is incremented by 1  
>>> del a	# Delete variable a and remove a's reference to 1  
>>> del b	# Delete variable b and dereference b to 1  
>>> print(c)	 # The final variable c still references 1 
1
>>>

Note: Python's delete is different from C's free and C + + delete. Because Python is a reference, python has a GC mechanism. Therefore, del statements act on variables, not data objects.

be careful:

1,Python You can assign the same value to multiple variables at the same time.
	>>> a=b=c=d=1

2,Python You can assign different values to multiple variables at the same time.
	>>> a,b,c=1,2,3

3,Python You can write multiple statements on the same line, separated by semicolons.
	>>> a=1;b=2

4,A variable can have references to different objects
	>>> a=1
	>>> a="qwww"

5,In mixed numerical calculation, integers are converted into floating-point numbers to participate in the operation.

7.Python numeric type conversion

  • When you need to convert the built-in type of data, you only need to use the data type as the function name.
    • int(x) converts x to an integer. The parameter can be a number or a string.
    • float(x) converts x to a floating point number.
    • complex(x) converts x to a complex number. The real part is x and the imaginary part is 0.
    • complex(x, y) converts X and y to a complex number. The real part is x and the imaginary part is y. X and y are numeric expressions.
>>> int(3.2)
3
>>> float(3)
3.0
>>> complex(3)
(3+0j)
>>> complex(1,2)
(1+2j)
>>>

8.Python sequence overview

The commonly used sequence structures in Python include lists, tuples, strings, dictionaries, collections, and objects such as range, zip, and filter, which also support many similar operations.

listtupleDictionariesaggregate
Type namelisttupledictset
DelimiterSquare brackets []Parentheses ()Braces {}Braces {}
Variableyesnoyesyes
Is it orderlyyesyesnono
Whether subscripts are supportedYes (use serial number as subscript)Yes (use serial number as subscript)Yes (use "key" as subscript)no
Element separatorcommacommacommacomma
Requirements for element formnothingnothingKeys: ValuesMust be hashable
Requirements for element valuesnothingnothing'key' must be hashableMust be hashable
Is the element repeatableyesyes"Key" cannot be repeated, and "value" can be repeatedno
Element lookup speedVery slowVery slowVery fastVery fast
Speed of adding and deleting elementsThe tail operation is fast and other positions are slownot allowfastfast

4. String

Strings in Python are immutable sequences, which are character sequences enclosed by delimiters such as single quotation marks ('), double quotation marks ("), three single quotation marks ('), or three double quotation marks (').
  single quotation marks, double quotation marks, three single quotation marks and three double quotation marks can be nested with each other to represent complex strings. For example, 'abc', '123', 'China', 'Python', 'Tom said,' Let's go '' (this type can not be escaped).
  an empty string is represented as' 'or' '.
  the string represented by the three quotation marks' 'or "" "can wrap lines and support strings with complex typesetting; the three quotation marks can also represent long comments in the program.
  there is no character type in python. In addition, single line comments in python are #, and multi line comments (block comments) are three quotation marks.

1. Create string

  • To create a string, you can create a string by assigning a character sequence enclosed by a string delimiter to the variable. For example:

    var1 = 'Hello World!'
    

2. Escape character

  • Common escape characters
Escape charactermeaningEscape charactermeaning
\At the end of the lineNewline character\000empty
\bBackspace to move the cursor to the previous column\\A slash\
\fPage feed\'Single quote '
\nNewline character\"Double quotation marks
\renter\oyyCharacter corresponding to octal yy number
\tHorizontal tab\xhhCharacters corresponding to 2-digit hexadecimal numbers
\vvertical tab \uhhhhA Unicode character represented by a 4-digit hexadecimal number
  • If the boundary character of the string is not in the string when defining the string, it can not be escaped.
>>> a="ssss\'ddd\'ddd"
>>> a
"ssss'ddd'ddd"
>>> a="ssss'ddd'ddd"
>>> a
"ssss'ddd'ddd"
  • If the boundary character of the string is in the string when defining the string, it must be escaped. \ it is not included in the string.
>>> a="ssss'ddd'd\"dd"
>>> a
'ssss\'ddd\'d"dd'
  • The letter R or r before the string delimiter indicates the original string. The special characters in the string are not escaped, but the last character of the string cannot be \. The original string is mainly used for regular expressions, file paths or URL s.
>>> path="C:\Windows\notepad.exe"
>>> print(path)		# The character \ NIS escaped as a newline character
C:\Windows
otepad.exe
>>> path=r"C:\Windows\notepad.exe"		# Original string, no characters are escaped
>>> print(path)
C:\Windows\notepad.exe
>>>
>>> x=r'dsepd\'		# error
  File "<stdin>", line 1
    x=r'dsepd\'
               ^
SyntaxError: EOL while scanning string literal
>>>    

3. String encoding

  • String encoding of Python 3. You can view the default string encoding of Python 3 through the following code:

    >>> sys.getdefaultencoding()
    'utf-8'
    >>>
    

encode() method

  • Encodes the string in the encoding format specified by encoding. The errors parameter can specify different error handling schemes.
  • The encode() method is a method provided for string type (str) to convert str type to bytes type. This process is also called "encoding".
  • The syntax format of encode() method is as follows:
str.encode(encoding='UTF-8',errors='strict')
	- encoding -- The encoding to use, such as"UTF-8". 
	- errors -- Set different error handling schemes. The default is 'strict',A coding error caused an error UnicodeError. 
>>> S = "Lazy C411";
>>> S_utf8 = S.encode("UTF-8")
>>> S_gbk = S.encode("GBK")
>>>
>>> print(S)
Lazy C411
>>>
>>> print("UTF-8 code:", S_utf8)
UTF-8 code: b'\xe6\x87\x92\xe7\xbe\x8a\xe7\xbe\x8a\xe7\x9a\x84C411'
>>> print("GBK code:", S_gbk)
GBK code: b'\xc0\xc1\xd1\xf2\xd1\xf2\xb5\xc4C411'
>>>
>>> print("UTF-8 decode:", S_utf8.decode('UTF-8', 'strict'))
UTF-8 Decoding: lazy sheep C411
>>> print("GBK decode:", S_gbk.decode('GBK', 'strict'))
GBK Decoding: lazy sheep C411
>>>
  • UTF-8 and GBK encoding and decoding
for example:
    >>> str = "this is string example....wow!!!"
    >>> S_utf8 = str.encode("UTF-8")
    >>> S_gbk = str.encode("GBK")
    >>>
    >>> print(str)
    this is string example....wow!!!
    >>>
    >>> print("UTF-8 code:", S_utf8)
    UTF-8 code: b'this is string example....wow!!!'
    >>> print("GBK code:", S_gbk)
    GBK code: b'this is string example....wow!!!'
    >>> print("UTF-8 decode:", S_utf8.decode('UTF-8', 'strict'))
    UTF-8 decode: this is string example....wow!!!
    >>> print("GBK decode:", S_gbk.decode('GBK', 'strict'))
    GBK decode: this is string example....wow!!!
    >>>
  
  • base64 encoding and decoding
    >>> import base64	
    >>> # str to string of bytes
    >>> str3 = str.encode(encoding ='utf-8',errors = 'strict')
    >>> # bytes are then base64 encoded
    >>> str4= base64.b64encode(str3)
    >>> # base64 decode again
    >>> print ("base64 code:",str4.decode())
    base64 code: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
    >>> enstr = base64.b64decode(str4.decode())
    >>> print("base64 decode:",enstr.decode())
    base64 decode: this is string example....wow!!!
    >>>

decode() method

  • In contrast to the encode() method, the decode() method is used to convert binary data of bytes type to str type. This process is also called "decoding".
  • The syntax format of the decode() method is as follows:
bytes.decode([encoding="utf-8"][,errors="strict"])
  • Description: encoding = "utf-8":
    • (1) Specifies the character encoding used in decoding. utf-8 format is adopted by default.
    • (2) When only this parameter is used in the method, "encoding =" can be omitted and the encoding method can be written directly.
  • Note: to decode byte type data, select the same format as the original encoding.
>>> str="bakery"
>>> bytes=str.encode()
>>> bytes.decode()
'bakery'
>>>
  • Note that if the encoding is not the default UTF-8 encoding, the same format as the encoding shall be selected during decoding, otherwise an exception will be thrown. The case is as follows:
>>> str="bakery"
>>> bytes=str.encode("GBK")
>>> bytes.decode()	# UTF-8 encoding is used by default, and the following exceptions will be thrown
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 0: invalid start byte
>>>

4. Built in functions ord(), chr() and str()

  • ord() and chr() are a pair of functions with opposite functions. ord() is used to return the ordinal number or Unicode code of a single character, chr() is used to return the character corresponding to an ordinal number, and str() directly converts any type parameter to a string.
>>> ord('d')
100
>>> chr(ord('R')+1)
'S'
>>> str(1253)
'1253'
>>> str((1,2,3))
'(1, 2, 3)'
>>> chr(65)
'A'
>>> str(5)
'5'
>>> str([1,2,3])
'[1, 2, 3]'
>>> str({1,2,3})
'{1, 2, 3}'
>>>

5. String operator

Operatordescribe
+String connection
*Duplicate output string
[]Get characters in string by index
[ : ]Intercepts a portion of a string
inMember operator – returns True if the string contains the given string
not inMember operator – returns True if the string does not contain the given string
r/ROriginal string – add the letter R or r before the first quotation mark of the string. All characters in the string are used directly according to the literal meaning, and special or unprintable characters are no longer escaped.
%format string
>>> str1='Python'
>>> str2='good'
>>> str3=str1+str2	# String connection
>>> print(str3)
Pythongood
>>> print(str1*3)	# Output string three times
PythonPythonPython
>>> print(3*str1)
PythonPython
>>>
  • Strings in Python can be indexed in two ways, starting with 0 from left to right and - 1 from right to left.

>>> str1='Python'
>>> print(str1[0]) # Output the first character of the string by index
P
>>> print(str1[2:5])	# Output characters from the third to the fifth
tho
>>> print(str1[0:-1])	# Output all characters from the first to the penultimate
Pytho
>>>
>>> 'y' in str1
True
>>> 'sd' in str1
False
>>> 'as' not in 'dffv'
True
>>>

6. Detailed usage of strip(), lstrip(), rstrip() in Python

Reference blog Park

In Python, there are three functions to remove leading and trailing characters and whitespace, which are as follows:

  • strip: used to remove leading and trailing characters and blank characters (including \ n, \ r, \ t, '', i.e. line feed, carriage return, tab and space);

  • lstrip: used to remove the opening characters and whitespace characters (including \ n, \ r, \ t, '', i.e. line feed, carriage return, tab and space);

  • rstrip: used to remove ending characters and blank characters (including \ n, \ r, \ t, '', i.e. line feed, carriage return, tab and space);

  • Note: these functions only delete the first and last characters, and the middle ones will not be deleted.

  • Usage:

string.strip([chars])
string.lstrip([chars])
string.rstrip([chars])
  • The parameter chars is optional. When chars is empty, the blank characters at the beginning and end of the string (including \ n, \ r, \ t, '') are deleted by default.
  • When chars is not empty, the function will be parsed into characters by chars, and then these characters will be removed.
  • It returns a copy of the string with the leading and trailing characters (or whitespace) removed, and the string itself will not change.

Examples are as follows:

  1. When chars is empty, whitespace characters (including '\ n', '\ r', '\ t', ') are deleted by default
>>> str = ' ab cd '
>>> str
' ab cd '
>>> str.strip() #Delete leading and trailing spaces
'ab cd'
>>> str.lstrip() #Remove leading spaces
'ab cd '
>>> str.rstrip() #Delete trailing spaces
' ab cd'
  1. When chars is not empty, the function will be parsed into characters by chars, and then these characters will be removed.
>>> str2 = '1a2b12c21'
>>> str2.strip('12') #Delete 1 and 2 at the beginning and end
'a2b12c'
>>> str2.lstrip('12') #Delete the first 1 and 2
'a2b12c21'
>>> str2.rstrip('12') #Delete ending 1 and 2
'1a2b12c'

7. String case conversion

  • str.lower(): converts uppercase letters in string str to lowercase letters.
  • str.upper(): converts lowercase letters in str to uppercase letters.
  • str.swapcase(): swap case in str.
  • str.capitalize(): returns a string with only the first capital letter.
>>> 'Adobe'.lower()
'adobe'
>>> 'Adobe'.upper()
'ADOBE'
>>> 'Adobe'.swapcase()
'aDOBE'
>>> 'Adobe'.capitalize()
'Adobe'
>>>
  • string.capwords(str[, sep]): use sep as the separator (if there is no parameter sep, the default is to use space as the separator), split the string str, then replace the first letter of each field with uppercase, set the letters of each field except the first letter to lowercase, and finally merge and connect them to form a new string.
  • Note: capwords(str) is a function in the string module. Before using it, you need to import the string module, that is, import string.
>>> import string
>>> string.capwords("ShaRP tools make good work.")
'Sharp Tools Make Good Work.'
>>>

8. String segmentation

  • str.split(s,num) [n]: split a string str into a list consisting of num+1 strings according to the separator specified in S (all empty characters by default, including spaces, line breaks (\ n), tabs (\ t), etc.). If it has [n], it indicates that the nth partition after segmentation is selected, and N indicates the subscript of the element in the returned list, starting from 0.

    >>> str='hello   world'
    >>> str.split()
    ['hello', 'world']
    >>>
    >>> str2="www.taobao.com"
    >>> str2.split('.',1)	# Separate once
    ['www', 'taobao.com']
    >>> str2.split('.')[2]	# Select the second slice after segmentation and return it as the result
    'com'
    >>> str2.split('.')[1]	# Select the first slice after segmentation and return it as the result
    'taobao'
    >>>
    
    >>> str2="www.taobao.com"
    >>> s1,s2,s3=str2.split('.',2)	# s1, s2 and s3 are assigned respectively to obtain the three cut parts
    >>> print(s1,s2,s3)
    www taobao com
    >>> s='call\nme\nbaby'
    >>> s.split('\n')
    ['call', 'me', 'baby']
    >>> s="hello!<[www.subeily.com.cn]>Good"
    >>> s.split('[')[1].split(']')[0]
    'www.subeily.com.cn'
    >>>
    

    partition() method

  • If the string contains the specified separator, a 3-element tuple is returned. The first is the substring to the left of the separator, the second is the separator itself, and the third is the substring to the right of the separator. If the string does not contain the specified delimiter, a 3-element tuple is returned. The first is the original string, the second is an empty string, and the third is an empty string.

>>> str="http://www.suse.edu.cn"
>>> str.partition("://")
('http', '://', 'www.suse.edu.cn')
>>> str.partition("b")
('http://www.suse.edu.cn', '', '')
>>>

String search: find(), rfind(), index(), rindex(), count()

  • The find() and rfind methods are used to find the first and last occurrence of a string in the specified range of another string (the whole string by default). If it does not exist, it returns - 1;

  • The index() and rindex() methods are used to return the position of the first and last occurrence of a string in the specified range of another string. If it does not exist, an exception will be thrown;

  • The count() method returns the number of times a string appears in the current string.

  • str.find(substr [,start [, end]]): returns the position of the first letter of the substr that appears for the first time in the specified range (the default is the whole string) in str. if there is no substr in str, it returns - 1.

    >>> 'He that can have patience.'.find('can')
    8
    >>> 'He that can have patience.'.find('aan')
    -1
    >>>
    
    >>> s="apple,peach,banana,peach,pear"
    >>> s.find("peach")
    6
    >>> s.find("peach",7)
    19
    >>> s.find("peach",7,20)
    -1
    >>> s.rfind('p')
    25
    >>> s.index('p')
    1
    >>> s.index('pe')
    6
    >>> s.index('pear')
    25
    >>> s.index('ppp')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: substring not found
    >>> s.count('p')
    5
    >>> s.count('pp')
    1
    >>> s.count('ppp')
    0
    >>>
    
    >>> str="this is really a string example....wow!!!"
    >>> substr="is"
    >>> print(str.rfind(substr))
    5
    >>> print(str.rfind(substr,0,10))
    5
    >>> print(str.rfind(substr,10,0))
    -1
    >>> print(str.find(substr))
    2
    >>> print(str.find(substr,0,10))
    2
    >>> print(str.find(substr,10,0))
    -1
    >>>
    

    String substitution

  • str.replace(oldstr, newstr [, count]): replace the oldstr string in str with the newstr string. If the count parameter is specified, it means that the replacement cannot exceed count times at most. If the count parameter is not specified, it means that all are replaced and how many are replaced.

  • str.count(substr[, start, [end]]): counts the number of substr occurrences in the string str. if the start position and end position are not specified, it means counting from beginning to end.

>>> str='This is a string example.This is a really string.'
>>> str.replace("is","was")
'Thwas was a string example.Thwas was a really string.'
>>> 'dfgfhfjbfyjhgfbfguhbdyutyukum'.count('df')
1
>>>

String mapping

  • str.maketrans(instr, outstr): used to create a conversion table (mapping table) for character mapping. The first parameter instr represents the string to be converted, and the second parameter outstr represents the target string to be converted. The length of two strings must be the same, which is a one-to-one correspondence.
  • str.translate(table): use the mapping table table generated by str.maketrans(instr, outstr) to map the string str.
>>> table=str.maketrans('abcdef','123456')	# Create a mapping table and convert 'abcdef' to '123456' one by one
>>> table
{97: 49, 98: 50, 99: 51, 100: 52, 101: 53, 102: 54}
>>> s1='Python is a greate programming language.I like it.'
>>> s1.translate(table)		# Use the mapping table table to map the string s1
'Python is 1 gr51t5 progr1mming l1ngu1g5.I lik5 it.'
>>> table=''.maketrans('0123456789','zero one two three four five six seven eight nine')
>>> '2021 September 11'.translate(table)
'September 11, 2012'
>>>

Determine the beginning and end of a string

  • str.startswitch (substr [, start, [End]]): used to check whether the string str starts with the string substr. If so, it returns True; otherwise, it returns False.
>>> s='Work makes the workman.'
>>> s.startswith('Work')	# Check the entire string
True
>>> s.startswith('the',11)
True
>>> s.startswith('the',12)
False
>>> s.startswith('the',12,13)
False
>>>
  • str.endswitch (substr [, start [, end]]): used to check whether the string str ends with the string substr. If so, it returns True; otherwise, it returns False.
>>> s='Constant dropping wears the stone.'
>>> s.endswith('stone.')
True
>>> s.endswith('ears',0,23)
True
>>>

Lists files with. md or. xmind extension in the specified directory

import os
items = os.listdir("F:\\java\\Github\\Blog-Java\\file\\02-Java Web") # Returns the list of files and folders under the specified path
newlist=[]
for names in items:
    if names.endswith((".md",".xmind")):
        newlist.append(names)
print(newlist)

Connection string

  • str.join(sequence): returns a new string generated after connecting the elements in the sequence through the specified character str.
  • Use the split() and join() methods to delete redundant white space characters in the string, and only one of the consecutive white space characters is reserved.
>>> str = "-"
>>> seq = ('a', 'b', 'c','d')
>>> str.join( seq )
'a-b-c-d'
>>> seq1 = ['Keep','on','going','never','give','up']
>>> print(' '.join(seq1))
Keep on going never give up
>>>
>>> seq2={'hello':1,'good':2,'boy':3,'world':4}
>>> '-'.join(seq2)
'hello-good-boy-world'
>>> ''.join(('/hello/','good/boy/','world'))
'/hello/good/boy/world'
>>>
>>> x = 'aaa      bb      c d e   fff    '
>>> ' '.join(x.split())		# Use spaces as connectors
'aaa bb c d e fff'
>>> ''.join(x.split())
'aaabbcdefff'
>>> '#'.join(x.split())
'aaa#bb#c#d#e#fff'
>>>

Determine whether the two strings are equivalent in the Python sense

def equavilent(s1, s2):
    if s1 == s2:
        return True
    elif ' '.join(s1.split()) == ' '.join(s2.split()):
        return True
    elif ''.join(s1.split()) == ''.join(s2.split()):
        return True
    else:
        return False
print(equavilent('pip list', 'pip    list'))    # True

Judge whether the string is all numbers, characters, etc

str.isalnum(): str All characters are numbers or letters, return Ture
str.isalpha(): str All characters are letters, return Ture
str.isdigit(): str All characters are numbers, return Ture
str.islower(): str All characters are lowercase, return Ture
str.isupper(): str All characters are uppercase, return Ture
str.istitle(): str All words are capitalized and return Ture
str.isspace(): str All characters are blank, return Ture
>>> '1234abcd'.isalnum()  # Returns True when all are composed of letters and numbers
True
>>> '1234abcd'.isalpha()  # Returns True when all letters are English letters
False
>>> '1234abcd'.isdigit()  # Returns True when all are numbers
False
>>> 'abcd'.isalpha()
True
>>> '1234.0'.isdigit()
False
>>> 'four'.isnumeric()    # isnumeric() method supports Chinese characters, numbers and Roman numerals
True
>>> '4526'.isdigit()
True
>>> 'six'.isdigit()
False
>>> 'six'.isdecimal()
False
>>> 'ⅣⅢⅩ'.isdecimal()
False
>>> 'ⅣⅢⅩ'.isdigit()
False
>>> 'ⅣⅢⅩ'.isnumeric()
True
>>>
isdigit()
    True: Unicode Numbers, byte Number (single byte), full angle number (double byte), Roman numeral
    False: Chinese numeral
    Error: nothing

isdecimal()
    True: Unicode Digit,, full angle digit (double byte)
    False: Roman numerals, Chinese numerals
    Error: byte Number (single byte)

isnumeric()
    True: Unicode Digit, full angle digit (double byte), Roman digit, Chinese character digit
    False: nothing
	Error: byte Number (single byte)

String alignment and filling

  • center(), ljust(), rjust(), returns a new string with the specified width. The original string appears in the new string in the center, left or right alignment. If the specified width is greater than the string length, it is filled with the specified character (space by default). zfill() returns a string of the specified width, filled with the character 0 on the left.
>>> 'Hello SpringBoot!'.center(20)	# Center aligned, filled with spaces
' Hello SpringBoot!  '
>>> 'Hello SpringBoot!'.center(20,'=')	# Center aligned, filled with character =
'=Hello SpringBoot!=='
>>> 'Hello SpringBoot!'.ljust(20,'=')	# Align left
'Hello SpringBoot!==='
>>> 'Hello SpringBoot!'.rjust(20,'=')	# Right align
'===Hello SpringBoot!'
>>> str="this is String exmaple!"
>>> print(str.zfill(40))
00000000000000000this is String exmaple!
>>>

9. String constant

String constants such as numbers, punctuation marks, English letters, uppercase English letters and lowercase English letters are defined in Python standard library string.

>>> import string
>>> string.ascii_letters      # All letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase   # All lowercase letters
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase   # All capital letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits           # All numbers 0-9
'0123456789'
>>>

Tags: Python Pycharm crawler

Posted on Sat, 20 Nov 2021 13:08:15 -0500 by Gibbs