Python Basics

Fundamentals of Python language

Python syntax features

notes

Single-Line Comments
#As a single line comment symbol, from # beginning to line feed, all the contents behind it are ignored by the Python compiler as the contents of comments

multiline comment

'''
Note content 1
 Note content 2
'''
# perhaps
"""
Note content 1
 Note content 2
"""

Chinese Notes

#Coding = coding
#-*-Coding: coding-*-

Encoding is the character encoding type used by the file, including utf-8, gbk and cp936

Code indent

Python programming language uses code indentation and colon: to distinguish the levels between codes. The colon at the end of the line and the indentation on the next line represent the beginning of a code block, and the end of the indentation represents the end of a code block.

Coding specification

Writing rules
1. Each import statement imports only one module
2. Do not add a semicolon at the end of the line:, and do not use a semicolon to put two commands on the same line
3. It is recommended that each line should not exceed 80 characters. If it exceeds, it is recommended to use () to implicitly connect multiple lines of content
4. Use the necessary blank lines to increase the readability of the code
5. It is recommended to use spaces on both sides of the operator, between function parameters, and on both sides of the comma "."
6. Avoid using the + and + = operators to accumulate strings in loops. Because strings are immutable, this creates unnecessary temporary objects
7. Properly use exception handling structure to improve program fault tolerance

Naming conventions
1. The module name shall be as short as possible, and all lowercase letters shall be used. Multiple letters can be separated by underscores, game_main and bmiex are recommended module names
2. The package name shall be as short as possible, and all lowercase letters shall be used. Underline is not recommended, com mr.book,com.mr is the recommended package name
3. The class name shall be capitalized
4. The classes inside the module are underlined _+ Pascal style class names. For example, the internal class in the BorrowBook class can be used_ BorrowBook naming
5. The naming rules for the attributes and methods of functions and classes are similar to those of modules. All lowercase letters are used, and multiple letters are separated by underscores
6. When naming constants, all uppercase letters can be used, and underscores can be used
7. Module variables or functions starting with a single underscore are protected
8. Instance variables or methods starting with double underscores are class private

variable

Reserved words and identifiers

Reserved words in Python are reserved by the system. Names of named functions, variables, classes, modules and other objects cannot be used
View command statements for keywords

import keyword
keyword.kwlist


Identifier naming rules
1. It is composed of letters, underscores and numbers, and the first character cannot be a number. Only a ~ z and a ~ z are allowed for characters
2. Reserved words in Python cannot be used
3. Case sensitive
4. Identifiers beginning with underscores in Python have special meanings
A class property that cannot be accessed directly by an identifier that begins with a single underscore
Identifiers that begin with a double underscore represent the private members of the class
Starting and ending with double underscores are special identifiers in Python, and int() represents the constructor

Python language allows the use of Chinese characters as identifiers, but it is strongly recommended not to do so!!!

variable

Variables in Python are names and labels; Use the lowercase letter l and the uppercase letter O carefully in naming

# Syntax format variable name = value
nickname = "Edviv"
# type() returns the variable type
print(type(nickname))
# id() get variable memory address
print(id(nickname))

Constant is the value that cannot be changed during program operation, but in the actual development process, after the constant is assigned for the first time, it can still be modified by other codes

Basic data type

number

In Python, a number type is provided to store these values, and it is an immutable data type; If you modify the value of a numeric variable, you will first store the value in the content, and then modify the variable to point to the new memory address

Integer: including positive integer, negative integer and 0; When it exceeds the calculation function of the computer itself, it will automatically switch to high-precision calculation

Octal integer: 0O or 0O
Hexadecimal integer: 0X or 0X

Floating point number: composed of integer and decimal parts
The str(a) function converts the value a into a string

Complex number: the imaginary part is represented by J or j, which means that the real part and imaginary part of a complex number are added; 3.14+1.5j real part 3.14; Imaginary part 1.5j

character string

String: it is a continuous character sequence, which can be a collection of all characters that can be represented by a computer. A string belongs to an immutable sequence, usually using ',', '', '', ''

# Precede the string delimiter quotation mark with the letter R or R, and the character is output as is
print("Wine of disappointment\x0a Cup of opportunity")
# Wine of disappointment
# Cup of opportunity
print(r"Wine of disappointment\x0a Cup of opportunity")
# Wine of disappointment \ x0a cup of opportunity
print(R"Wine of disappointment\x0a Cup of opportunity")
# Wine of disappointment \ x0a cup of opportunity

Boolean type

In Python, the identifiers True and False are interpreted as Boolean values, with True representing 1 and False representing 0

Data type conversion

Number = = = > string = = > int (x) = = = > string = = > output

functioneffect
int(x)Convert x to integer type
float(x)Convert x to float type
complex(real[,imag])Create a complex number
str(x)Convert x to string
repr(x)Convert x to an expression string
eval(str)Evaluates a valid Python expression in a string and returns an object
chr(x)Convert x to one character
ord(x)Converts a character x to its corresponding integer value
hex(x)Converts an integer x to a hexadecimal string
otc(x)Converts an integer x to an octal string

Basic input and output

input() function input

Use the built-in function input() to receive the contents entered by the user's keyboard. In Python 3 No matter what numbers or characters are entered in X, they are read as strings. To get the desired data type, data type conversion is required

print() function output

Basic syntax format: Print (output content)
In Python, by default, the output of a print() statement will wrap automatically. If you want to output multiple contents without wrapping, you can separate the contents to be output with commas with English half width

Operators and Expressions

operator

Arithmetic operator

operatorexplain
+plus
-reduce
*ride
/except
%Seeking remainder
//Take integer
**power

Use% for remainder. If the second operand is negative, the result is negative; Use / or / / the divisor cannot be 0, otherwise an exception will occur. Python 3.x, 7 / 2 = 3.5, python 2 X medium 7 / 2 = 3

Assignment Operators

=The value on the right is assigned to the variable on the left

Compare relational operators

operatoreffect
>greater than
<less than
==be equal to
!=Not equal to
>=Greater than or equal to
<=Less than or equal to

Logical operator

operatormeaning
andLogic and
orLogical or
notLogical non

Bitwise Operators

&(bitwise AND): when the binary bit of the corresponding position of two operands is 1. The result is 1, otherwise the result is 0, and the precision is the same as the operand with high precision

|(bitwise OR): when the binary bits of the corresponding positions of two operands are 0. The result is 0, otherwise the result is 1, and the precision is the same as the operand with high precision

^(bitwise exclusive or): the binary bits of the corresponding positions of two operands are different. The result is 1, otherwise the result is 0, and the precision is the same as the operand with high precision

~(reverse by bit): change the 1 in the binary corresponding to the operand to 0, and 0 to 1

< < (left shift operator): move a binary operand to the left by the specified number of bits, the overflow bits on the left are discarded, the empty bits on the right are filled with 0, and the left shift operator is equivalent to multiplying by 2 n 2^n 2n

>>(shift right operator): moves a binary operand to the right by the specified number of bits, and the overflow bit at the right end is discarded. When the operand is negative, the left is supplemented by 1, and when the operand is positive, the left is supplemented by 0

Operator priority

typeexplain
**power
~,+,-Take negative, positive and negative signs
*,/ ,%,//Arithmetic operator
+,-Arithmetic operator
<<,>>Shift left and right in displacement operator
&Bitwise AND
^Bitwise XOR
|Bitwise OR
<,<=,>,>=,!=,==Comparison operator

Priority decreases from top to bottom

Conditional expression

a = 10
b = 6
if a > b:
    r = a
else :
    r = b
# equivalence
a = 10
b = 6
r = a if a > b else b
# If a > b is True, r = a is returned, otherwise r = b is returned

Process control statement

Program structure: sequence structure, selection structure and loop structure

Select statement

There is no switch statement in Python. When the value of the if expression is a non-zero number or a non empty string, the condition is considered to be true
The simplest if statement

if expression:
    Statement block

if... else statement

if expression:
    Statement block 1
else
    Statement block 2
# Equivalent below
 Statement 1 if expression else Statement 2

if... elif... else statement

if Expression 1:
    Statement block 1
elif Expression 2:
    Statement block 2
elif Expression 3:
    Statement block 3
...
else:
    Statement block n

Circular statement

There is no do... while loop in Python
while loop

while Conditional expression:
    Circulatory body

for loop

for Iterative variable in object:
    Circulatory body

range(start, end, step)
start: used to specify the starting value of the count. If omitted, it starts from 0
End: Specifies the end value of the count and cannot be omitted. The value obtained by range(7) is 0 ~ 6
Step: used for the interval between two numbers. If omitted, the step is 1

range(): if there is only one parameter, it means end. If there are two parameters, it means start and end are specified. Only when all three parameters exist, the last one means step

Python 3.x: Output a line

# print(i, end = 'separator')
for i in range(50):
    if(i%3 == 2 and i%5 == 3):
        print(i, end = ' ')

break, continue, pass statements

break statement: end this cycle
continue statement: end this inner loop
pass statement: do nothing to occupy the space

Lists and tuples

sequence

Indexes

Sequence structures mainly include: list, tuple, set, dictionary and string
Collections and dictionaries do not support index, slice, add, and multiply operations

Positive index
elementElement 1Element 2ElementElement n
Index subscript01...n - 1
Negative index
elementElement 1Element 2ElementElement n
Index subscript- ( n - 1)-( n - 2 )...- 1

section

# Slicing can generate a new sequence
# Syntax format
sname[start: end : step]
# sname: name of the sequence
# start: the position where the slice starts, including this position. If it is not specified, it defaults to 0
# end: indicates the cut-off position of the slice, excluding this position. If it is not specified, the default sequence length is
# Step: indicates the step size of the slice. If omitted, it defaults to 1
# sname [:] means to copy the entire sequence

Sequence addition

Python supports the addition of two sequences of the same type, that is, the + operator is used to realize the connection operation. Sequences of the same type refer to the same list, tuple, string, etc., and the element types in the sequence can be different

multiplication

Multiplying an n by a sequence will get a new sequence. The content of the new sequence is the result of the original sequence being repeated n times

in checks whether an element is a member of a sequence

value in sequence
# value the element to check
# Sequence represents the specified sequence
# not in checks whether an element is not included in the sequence

Built in function

functionexplain
list()Convert sequence to list
str()Convert sequence to string
sum()Count elements and
sorted()Sort elements
reversed()Elements in reverse sequence
enumerate()Combine the sequences into an index sequence
len()Length of count sequence
max()Returns the largest element in the sequence
min()Returns the minimum value in the sequence

list

List create delete

=Assign a list to a variable

listname = [ element1, element2, ... ,element n]
# listname indicates the name of the list
# element1 ... elementn represents the elements in the list, and the number is unlimited 

Create an empty list

emptylist = []

Create a list of values

list(range(10, 20, 2))

Delete list

del listname

In actual development, Python's built-in garbage collection mechanism will automatically destroy unused lists, and python will automatically recycle them even if they are not manually deleted

datetime. datetime. The now () method obtains the current date, and the weekday() method obtains the week from the date time object, one of the values 0 ~ 6

Traversal list

The for loop can only output the value of the element. The combination of enumerate() can output the index value and element content at the same time

for item in listname:
    # Output item

for index, item in enumerate(listname)
    # Output index and item

# Index: the index used to hold the element
# item: used to save the obtained element value
# listname: list name

List add modify delete

+Or append() method: use this method to add elements to the list

listname.append(obj)
# Add an element at the end of the list

extend: adds all elements in one list to another list

# Append the contents of seq to listname
listname.extend(seq)
# listname original list
# seq added list

The element in the list only needs to get the element through the index, and then re assign its value

del: delete by index
remove(value): deletes all elements in the list that are the same as value according to the element value

List calculation

count() method: judge the number of occurrences of the specified element

listname.count(obj)
# listname list name
# obj indicates the object to judge whether it exists

index() method: get the position where the specified element appears for the first time in the list

listname.index(obj)
# listname: indicates the name of the list
# obj: indicates the object to find. If the object does not exist, an exception will be thrown
# Return value: the index value that appears for the first time

sum() function: sum of elements in the list of statistical values

sum(iterable[:])
# iterable: indicates the list to be counted
# [:] if not specified, the default is 0

sort list

sort() method: sort the elements in the original list. After sorting, the order of the elements in the original list will change. It is not well supported for Chinese

listname.sort(key=None, reverse=False)
# listname: indicates the list to sort
# Key: specifies a comparison key to extract from each list element
# key=str.lower is not case sensitive when sorting
# reverse: specify True to sort in descending order, False to sort in ascending order, and the default is ascending order

sorted() function: sort the list, and the element order of the original sequence remains unchanged.

sorted(iterable, key = None, reverse = False)
# iterable: indicates the sequence to be sorted
# key: specifies to extract a keyboard for comparison from each element
# key = str.lower indicates that sorting is case insensitive
# reverse: specify True to indicate descending order; If it is specified as False, it indicates ascending order, and the default is ascending order

List derivation

Generates a list of values in the specified range

# list=[Expression for var in range]
# List: indicates the name of the generated list
# Expression: an expression that evaluates the elements of a new list
# var: loop variable
# Range: the range object generated by the range() function
# Randomly generate 10 numbers between [10, 100]
import random
randomnumber = [random.randint(10,100) for i in range(10)]
print(randomnumber)

Generate a list of specified requirements

# newlist = [Expression for var in list]
# newlist: indicates the name of the newly generated list
# Expression: an expression that evaluates the elements of a new list
# var: variable
# List: the original list used to generate a new list
ago = [10, 20]
now = [x*2 for x in ago]
print(ago)
print(now)

Select the qualified elements in the list to form a new list

# newlist = [Expression for var in list if condition]
# newlist: indicates the name of the newly generated list
# Expression: an expression that evaluates the elements of a new list
# var: variable with the value of each element in the following list
# List: the original list used to generate a new list
# Condition: a condition expression that specifies a filter condition
ago = [10, 20]
now = [x for x in ago if x > 15]
print(ago)
print(now)

2D list

import random
arr = []           #Create an empty list
for i in range(5): # 5 lines
    arr.append([]) # Add another empty list to the empty list
    for j in range(3):
        arr[i].append(random.randint(1,5)) # Add element to inner list

for i in range(5): # Output list
    print(arr[i])

List derivation creation

# Create a 2D list of 4 rows and 5 columns
arr = [[j for j in range(5)] for i in range(4)]
# Available for listname [subscript 1] [subscript 2]
# listname: indicates the name of the list
# Subscript 1: indicates the row in the list, and the subscript value starts from 0
# Subscript 2: indicates the column in the list. The subscript value starts from 0

tuple

Tuple: it is an immutable sequence. Formally, all elements of a tuple are placed in a pair of parentheses (), and two adjacent elements are separated; In terms of content, any type of content such as integer, real number, string, list and tuple can be put into tuples. In the same tuple, the types of elements can be different because there is no relationship between them. Tuples are used to save the unmodifiable content in the program

Tuple operation

By separating a set of values with commas, Python can consider it a tuple
Create empty tuple

emptytuple = ()

Empty tuples can be used to pass a null value to a function or return a null value

Create a numeric tuple

# tuple(data)
# Data represents data that can be converted to tuples
# The data type can be a range object, a string, a tuple, or other iteratable type of data

Delete tuple

# del tuplename
# Tuplename: indicates the name of the tuple to be deleted

del statements are not commonly used in actual development. Python's built-in garbage collection mechanism will automatically destroy unused tuples
Access tuple element
Get the specified element by slicing

arr = tuple(range(1,20,2))
print(arr[:3])

enumerate() function: combine a traversable data object into an index sequence, and list the data and data subscripts at the same time

nowarr = ("Edviv","Lily","Bob","Tom","Hily","Cboy")
for index, item in enumerate(nowarr):
    if index%3 == 0 and index:
        print()                     # Output wrap
        print(item + " ", end = " ")
    else:
        print(item + " ", end = " ")

Tuple is an immutable sequence, and its single element value cannot be modified, but it can be re assigned; When tuples are connected, the contents of the connection must all be tuples

Tuple derivation

The result generated by tuple derivation is not a tuple or list, but a generator object_ next_ (): output each element by the method of, and then convert the generator object into tuple output; No matter which method you take to traverse, if you use the generator object again, you must recreate a generator object, because after traversal, the original generator object no longer exists

import random   # Import random standard library
ago = (random.randint(10,50) for i in range(5)) # Build generator object
print(ago.__next__()) # Output first element
now = tuple(ago)  # Convert to tuple
print(now)

The difference between tuples and lists

Tuples and lists are sequences, and they can store a set of elements in a specific order, with unlimited types

Differences between lists and tuples:
1. The list is a variable sequence, and its elements can be modified or deleted at any time; Tuples are immutable sequences, and the elements in them cannot be modified unless they are replaced as a whole
2. List elements can be added and modified using methods such as append(), extend(), insert(), remove(), pop(). Tuples do not have these methods because elements cannot be added, modified, or deleted
3. The list can use slices to access and modify the elements in the list; Tuples also support slicing, but it only supports accessing elements in tuples through slicing, and does not support modification
4. Tuples have faster access and processing speed than lists; If you only need to access the elements without any modification, it is recommended to use tuples
5. The list cannot be used as the key of the dictionary, but the tuple can

Dictionaries and collections

Dictionaries

Main features of Dictionary: similar to C/C + + and Map in Java
1. Read by key instead of index
2. A dictionary is an unordered collection of arbitrary objects
3. Dictionaries are variable and can be nested arbitrarily
4. The key in the dictionary must be unique. If it appears multiple times, the last value will be remembered
5. The keys in the dictionary must be immutable, so you can use numbers, strings or tuples, but you can't use lists
Dictionary creation:

# dictionary = {'key1':'value1','key2':'value2',...,'keyn':'valuen',}
# Dictionary: indicates the name of the dictionary
# key1, ...,  Key: represents the key of the element. It must be unique and immutable
# value1, ..., valuen: represents the value of an element. It can be any data type, not unique

Create an empty dictionary:
Dictionary = {} or dictionary = dict()

Create dictionary through mapping function:

# dictionary = dict(zip(list1, list2))
# Dictionary: indicates the name of the dictionary
# zip() function: used to combine the elements in the corresponding positions of multiple lists or tuples into tuples, and return the zip object containing these contents
# list1: represents a list that specifies the key to generate the dictionary
# list2: represents a list, which is used to specify the values to generate the dictionary
key = ['Edviv', 'Bob', 'Tom']  # List as key
age = ['23', '24', '19']       # List as values
Map = dict(zip(key, age))      # Convert to dictionary
print(Map)                     # Output converted dictionary

Key value pair create Dictionary:

# dictionary = dict(key1 = value1, ..., keyn = valuen)
# Dictionary: indicates the name of the dictionary
# key1, ...,  Key: represents the key of the element. It must be unique and immutable
# value1, ..., valuen: represents the value of an element, which can be any data type
dictionary = dict(Edviv = '22', Bob = '20')
print(dictionary)

fromkeys() method: create a dictionary with an empty value

# dictionary = dict.fromkeys(list1)
# Dictionary: indicates the name of the dictionary
# list1: list of keys as dictionaries
list1 = ['Edviv', 'Bob']
dictionary = dict.fromkeys(list1)
print(dictionary)

del dictionary delete dictionary
dictionary.clear() clears all elements of the dictionary
dictionary.get() method: gets the value of the specified key

Traverse Dictionary:
items() method: get the "key value pair" list of the dictionary

list1 = ['Edviv', 'Bob']
list2 = ['22', '20']
dictionary = dict(zip(list1,list2))
for item in dictionary.items():
    print(item)
# Specific keys and values
for key, value in dictionary.items():
    print(key, value)

Add an element to the dictionary: dictionary[key] = value
Dictionary: indicates the name of the dictionary
Key: the key to add an element. It must be unique and immutable
Value: represents the value of the element

Dictionary derivation

import random
randomdict = {i : random.randint(1,10) for i in range(1,4)}
print(randomdict)

name = ['Edviv','Bob','Tom']        # List of keys
sign = ['Gemini', 'aquarius', 'sagittarius'] # List of values
nowdictionary = {i:j for i, j in zip(name, sign)}
print(nowdictionary)

aggregate

Sets are divided into set and frozenset
{} create collection

# setname = {element1, ...,elementn}
# setname indicates the name of the collection
# element1, ...,elementn represents the elements in the collection, and the number is unlimited
set1 = {1, 3, 5, 7, 9, 4, 0, 0, 1}
print(set1)
# Create a collection, enter duplicate elements, and only one will be retained

The set() function converts iteratable objects such as lists and tuples into collections

# setname = set(iteration)
# setname: indicates the name of the collection
# iteration: represents the iteratable object to be converted into a collection, which can be a list, tuple, range object, etc
# Returns a collection that does not duplicate
set2 = set([1, 5, 4, 6])
print(set2)

When creating an empty collection, you can only use set() instead of a pair of braces "{}". Because "{}" is used in Python to create an empty dictionary, the set() function is used to create the collection

Add elements to the collection

# setname.add(element)
# setname: indicates the collection of added elements
# Element: indicates the content of the element to be added. Only string, number and Boolean types can be used
# Iteratable objects such as lists and tuples cannot be used

setname.pop(): delete an element
setname.clear(): clear the collection
setname.remove(iteration): deletes the specified element

set2 = set([1, 5, 4, 6]) # Create collection
print(set2)
set2.add(10)            # Add an element
print(set2)
set2.pop()              # Delete an element
print(set2)
set2.remove(10)        # Deletes the specified element
print(set2)
set2.clear()           # Empty collection
print(set2)

&: intersection of two sets
|: Union of two sets
-: perform difference set operation on two sets
^: perform difference set operation on two sets

character string

str stands for Unicode characters
bytes represents binary data

String encoding conversion

encode() method: it is a method of str object, which is used to convert string into binary data (i.e. bytes) "encoding"

# str.encode([encoding="utf-8"][,errors="strict"])
# str: represents the string to be converted
"""
 encoding="utf-8": Optional parameters,Specifies the character encoding to use when transcoding,default UTF-8,It can be set in simplified Chinese gb2312,
 Only one parameter,The preceding can be omitted"encoding=",Direct coding
"""

"""
errors="strict": Optional parameters,Used to specify how errors are handled,Its optional value strict meet
 An exception is thrown when an illegal character is detected ignore Ignore illegal characters replace use ? Replace illegal characters
 or xmlcharrefreplace use XML Character references, etc,The default value is strict
"""

decode(): a method of a bytes object, which is used to convert binary data into a string and "decode"

# bytes.decode([encoding="utf-8"][,errors="strict"])
# bytes: indicates the binary data to be converted
"""
 encoding="utf-8": Optional parameters,Used to specify the character encoding used for decoding,default UTF-8,It can be set in simplified Chinese gb2312
 Only one parameter,The preceding can be omitted"encoding=",Direct write coding
"""

"""
errors="strict": Optional parameters,Used to specify how errors are handled,Its optional value strict meet
 An exception is thrown when an illegal character is detected ignore Ignore illegal characters replace use ? Replace illegal characters
 or xmlcharrefreplace use XML Character references, etc,The default value is strict
"""

verse = "I am Edviv"
byte = verse.encode('utf-8') # code
print(verse)                 # Original code
print(byte)                  # binary data
print(byte.decode("UTF-8"))  # decode

String common operations

+The operator can splice multiple strings and produce a string object
len() function: when calculating the length of a string, English, numbers and Chinese characters are not distinguished, so all characters are considered to be one
UTF-8 coding is adopted, and Chinese characters account for 3 bytes; When GBK or GB2312 is adopted, Chinese characters account for 2 bytes; In Python, numbers, English, decimal points, underscores, and spaces occupy one byte
Intercept string

# string[start : end : step]
# String: indicates the string to be intercepted
# start: indicates the index of the first character to be intercepted. If not specified, it defaults to 0
# end: indicates the index of the last character to be intercepted, excluding this character. If not specified, the length of the default string
# Step: indicates the step size of the slice. If omitted, it defaults to 1

split(): divides a string into a string list according to the specified separator. The elements of the list do not include the separator

# str.split(seq, maxsplit)
# str: represents the string to be split
# seq: Specifies the separator, which can contain multiple characters. The default is None, that is, all empty characters
'''
maxsplit: Optional parameters,Used to specify the number of divisions,If not specified or-1,There is no limit to the number of separations
 Otherwise, the maximum number of elements in the returned result list is maxsplit + 1
'''
# Return value: list of split strings

split(): if no parameter is specified, the default is to use the white space character for segmentation. At this time, no matter how many spaces or white space characters exist, they will be divided as a separator
Merge string

# strnew = string.join(iterable)
# strnew: represents the new string generated after merging
# String: string type, used to specify the separator when merging
# iterable: iteratable object. All elements in the iterated object will be merged into a new string
# string as boundary points

Retrieve string
count(): retrieves the number of occurrences of the specified string in another string. If the retrieved string does not exist, it returns 0; otherwise, it returns the number of occurrences

# str.count(sub[ ,start[ ,end]])
# str: represents the original string
# sub: indicates the substring to retrieve
# Start: optional parameter, indicating the index of the starting position of the retrieval range. If it is not specified, the retrieval will start from the beginning
# End: optional parameter, indicating the index of the end position of the retrieval range. If it is not specified, it will be retrieved until the end

find() method: retrieve whether the specified substring is included; Returns - 1 if the retrieved string does not exist, otherwise returns the index when the substring first appears

# str.find(sub[ ,start[ ,end]])
# str: represents the original string
# sub: indicates the substring to retrieve
# Start: optional parameter, indicating the index of the starting position of the retrieval range. If it is not specified, the retrieval will start from the beginning
# End: optional parameter, indicating the index of the end position of the retrieval range. If it is not specified, it will be retrieved until the end

index() method: used to retrieve whether the specified substring is included. An exception will be thrown when the specified string does not exist

# str.index(sub[ ,start[ ,end]])
# str: represents the original string
# sub: indicates the substring to retrieve
# Start: optional parameter, indicating the index of the starting position of the retrieval range. If it is not specified, the retrieval will start from the beginning
# End: optional parameter, indicating the index of the end position of the retrieval range. If it is not specified, it will be retrieved until the end

Startswitch () method: retrieves whether the string starts with the specified substring; Returns True if yes, False otherwise

# str.startswith(prefix[ ,end]])
# str: represents the original string
# prefix: indicates the substring to retrieve
# Start: optional parameter, indicating the index of the starting position of the retrieval range. If it is not specified, the retrieval will start from the beginning
# End: optional parameter, indicating the index of the end position of the retrieval range. If it is not specified, it will be retrieved until the end

Endswitch(): retrieves whether the string ends with the specified substring; Returns True if yes, False otherwise

# str.endswith(suffix[ ,start[ ,end]])
# str: represents the original string
# suffix: indicates the substring to retrieve
# Start: optional parameter, indicating the index of the starting position of the retrieval range. If it is not specified, the retrieval will start from the beginning
# End: optional parameter, indicating the index of the end position of the retrieval range. If it is not specified, it will be retrieved until the end

str.lower(): converts all uppercase letters in str to lowercase letters
str.upper(): converts all lowercase letters in str to uppercase letters

Remove spaces and special characters from the string

strip() method: used to remove spaces and special characters on the left and right sides

# str.strip([chars])
# str: string to remove spaces
'''
chars: Optional parameters,Specifies the character to remove,Multiple can be specified
 If not specified chars parameter,By default, spaces and tabs are removed\t,Carriage return\r,Newline character\n etc.
'''

lstrip() method: used to remove the spaces and special strings on the left side of the string

# str.lstrip([chars])
# str: string to remove spaces
'''
chars: Optional parameters,Specifies the character to remove,Multiple can be specified
 If not specified chars parameter,By default, spaces and tabs are removed\t,Carriage return\r,Newline character\n etc.
'''

rstrip() method: used to remove spaces and special characters on the right side of the string

# str.rstrip([chars])
# str: string to remove spaces
'''
chars: Optional parameters,Specifies the character to remove,Multiple can be specified
 If not specified chars parameter,By default, spaces and tabs are removed\t,Carriage return\r,Newline character\n etc.
'''

format string

Format string means to make a template, reserve several spaces in the template, and then fill in the corresponding contents as needed. These spaces need to be marked by the specified symbols, which will not be displayed

In Python, to format strings, you can use the% operator;% [-] [+] [0][m][.n] format character% exp
-: optional parameter, used to specify left alignment, unsigned before positive numbers and minus sign before negative numbers
+: optional parameter, used to specify the right alignment, with a plus sign before positive numbers and a minus sign before negative numbers
0: optional parameter, indicating right alignment. The positive number is preceded by a meta symbol, the negative number is preceded by a minus sign, and the blank space is filled with 0 (generally used with the m parameter)
m: Optional parameter indicating occupancy width
. n: optional parameter, indicating the number of digits reserved after the decimal point
Format character: used to specify the type

Common formatting characters
Format characterexplainFormat characterexplain
%sString (displayed in str())%rString (displayed in repr())
%cSingle character%oOctal integer
%d or% iDecimal integer%eIndex (base is written as e)
%xHexadecimal integer%EIndex (base is written as E)
%F or% FFloating point number%%Character%

format() method: used for string formatting

'''
str.format(args)
str: Specifies the display style of the string
args: Specifies the item to convert,If there are multiple,Comma separated
 When creating a template,Need to use {} and : Specify placeholder
{[index][:[[fill]align][sign][#][width][.precision][type]]}
index: Optional parameters,Specifies the index position of the object to be formatted in the parameter list,Index value starts at 0,If omitted, it is automatically assigned according to the order of values
fill: Optional parameters,The character used to specify the space to fill

align: Optional parameters,Lets you specify the alignment;Value is < Indicates left alignment of content; Value is > Indicates right alignment of content; Value is = Indicates right alignment of content,Place symbol in
 On the far left of the fill,And valid only for numeric types; Value is ^ Indicates that the content is centered,Need cooperation width Use together

sign: Optional parameters,Used to specify the signed or unsigned number;Value is + Indicates a positive number plus a plus sign,Negative number plus minus sign; Value is - Indicates that the positive number remains unchanged,Negative number plus minus sign;Values are blank tables
 Positive numbers plus spaces,Negative number plus minus sign

#: Optional parameters,For binary, octal, and hexadecimal,If you add #, indicating that the 0b/0o/0x prefix will be displayed, otherwise the prefix will not be displayed
width: Optional parameters,Used to specify the occupied width
.precision: Optional parameters,Specifies the number of decimal places to keep
type: Optional parameters,Used to specify the type
'''
Formatting characters commonly used in the formcat() method
Format characterexplainFormat characterexplain
SFormat string typebAutomatically convert decimal integers to binary representation and then format
DDecimal integeroAutomatically convert decimal integers to octal representation and then format
CAutomatically convert decimal integers to corresponding Unicode charactersX or XAutomatically convert decimal integers to hexadecimal representation and then format
E or eReformat into scientific notation representationF or FConvert to floating point number (6 digits after the default decimal point) and then format
G or GAutomatically switch between E and f or E and F%Display percentage (6 decimal places by default)




Keywords: Python Back-end

Added by Mobile on Mon, 10 Jan 2022 17:56:22 +0200