Object-oriented language (Python) - formatting strings, operators


 When you count profit, you count the world's profit; when you seek fame, you seek eternal fame


——Lungcen

Table of contents

Knowledge of Python

 The advantages of python over other languages

Python data types and operators

a weakly typed language

(int) integer type

Base Conversion and Number Separators

 (float) decimal/floating point

(complex) complex type

Detailed explanation of the string

(bytes) type and usage

 (bool) Boolean type

Human-computer interaction - input() function, print() function

 character

format string

 conversion specifier

Minimum output width 

alignment, decimal precision

escape character

 type conversion

operator

 arithmetic operator

 bitwise operator

 assignment operator

 comparison operator

 Logical Operators

Ternary operator

Priority and associativity 



Knowledge of Python


 The advantages of python over other languages

The 21st century is an era of intelligence and an era of computers. Since AI is composed of top talents in other fields, and they can't spend a lot of time learning languages ​​​​such as Java, an introduction         is created. The beautiful, easy-to-learn, and closest programming language to natural language— Python , has gradually become the first development language in the era of artificial intelligence and big data.

Python data types and operators

Python data types are mainly divided into seven categories:

        Numbers : (int, float)

        bool (Boolean) : True, False

        String (string) : pairs of single, double, triple quotes

        List (list) : square brackets [1, 2, 3, 4]

        Tuple : Parentheses (1, 2, 3, 4)

        Set (collection) : braces {1, 2, 3, 4}

        Dictionary (dictionary) : braces {name: Li Hua, age: 18}

a weakly typed language

        In a strongly typed programming language, when defining a variable, the type of the variable must be specified, and the assigned data must also be of the same type. C language, C++, and Java are representatives of strongly typed languages.

        Variables in weakly typed languages ​​can be assigned directly without declaration , and assigning a value to a variable that does not exist is equivalent to defining a new variable. The data type of a variable can be changed at any time.

        In fact, there are not many weak types, which means that there are no types. It just means that the requirements for types are not very strict . You don’t need to pay attention to types when writing code, but there are still types inside the programming language .

(int) integer type

Integers are numbers without a fractional part. Integers in mathematics include positive integers, 0, and negative integers.

Integers in Python are typeless, or it has only one type of integer.

The value range of Python integers is unlimited , no matter how large or small the number, Python can easily handle it.

Base Conversion and Number Separators

1) Decimal form : The common integer is the decimal form, which is composed of ten numbers from 0 to 9.

2) Binary form : It consists of two numbers 0 and 1, and starts with 0b or 0B when written.

3) Octal form : Octal integers consist of eight numbers from 0 to 7, starting with 0o or 0O. The first symbol is the number 0, and the second symbol is the uppercase or lowercase letter O. 

4) Hexadecimal format : It consists of ten numbers from 0 to 9 and six letters from A to F (or a to f), and starts with 0x or 0X when writing.

Number separator: used to identify the size of the number of digits

a = 2 #十进制
b = 0b10 #二进制
c = 0o2 #八进制
d = 0x2 #十六进制

e = 12345
f = 12_345 #便于认识大小
print(a,b) #输出的两个数是一样的

 (float) decimal/floating point

1. Decimal form

        1.2, 23.4, 567.8

2. Index form

        (aEn aen) 1E2 1e2 is equivalent to 1x10^2

         a is the mantissa, which is a decimal number; n is the exponent, which is a decimal integer

        It is a decimal as long as it is written in exponential form , even if its final value looks like an integer.

        For example 14E3 is equivalent to 14000, but 14E3 is a decimal.

(complex) complex type

Complex numbers, I believe everyone may have a little impression, complex numbers are composed of real part (real) and imaginary part (imag), which is a+bi , and the square of i is -1 .

a1 = 1 + 2j
print("Value: ", a1)
print("Type", type(a1))

a2 = 5 - 1j
print("Value: ", a2)

print("加法: ", a1+a2) #对复数进行简单计算
print("乘法: ", a1*a2)

Detailed explanation of the string

1. If there are quotation marks in the string

        1. Escaping

        2. Double quotes include single quotes

        3. Single quotes wrap double quotes

2. If the string you input is very long, an error will be reported if you directly change the line in the work area, then you can add a backslash \ at the end of the line to change the line in the work area

3. Long strings are very long, but you don’t want to add backslashes, you can use three double quotes """ or three single quotes''' 

#需要用\进行转义,不然会报错的
str1 = 'I\'m GOD!'
str2 = "英文的双引号是\",中文的双引号是“"

#使用双引号包围含有单引号的字符串
str1 = "I'm GOD!"
#使用单引号包围含有双引号的字符串
str2 = '英文的双引号是",中文的双引号是“'

s1 = 'kljfdsklhf dshfj dfjk fdasfksdhf \
kldshf ksdhf ncbv hsf jbahf oiahf. I a b  sd.'

s2 = """kljfdsklhf dshfj dfjk fdasfksdhf
kldshf ksdhf ncbv hsf jbahf oiahf.I a b  sd."""

(bytes) type and usage

Comparison of bytes and strings:

(1) The string is composed of several characters, and the operation is performed in units of characters ;

         A byte string is composed of several bytes, and operations are performed in units of bytes .

(2) Byte strings and character strings are basically the same in all the methods they support except for the different data units they operate on.

(3) Both byte strings and character strings are immutable sequences , and data cannot be added or deleted at will.

bytes is only responsible for storing data in the form of a sequence of bytes (binary form)

1. If the contents of the string are all ASCII characters, then directly add the b prefix in front of the string to convert it into bytes.

2. bytes is a class, calling its construction method, namely bytes() , can convert a string into bytes according to the specified character set ; if no character set is specified, UTF-8 is used by default.

3. The string itself has an encode() method, which is specially used to convert the string into the corresponding byte string according to the specified character set ; if the character set is not specified, UTF-8 is used by default.

4. The bytes class also has a decode() method, through which the bytes object can be converted into a string

#通过构造函数创建空 bytes
b1 = bytes()
#通过空字符串创建空 bytes
b2 = b''
#通过b前缀将字符串转换成 bytes
b3 = b'http://www.baidu.com/python/'
#为 bytes() 方法指定字符集
b4 = bytes('百度', encoding='UTF-8')
#通过 encode() 方法将字符串转换成 bytes
b5 = "百度".encode('UTF-8')

# b4、b5的 输出如下:
# b'\xe7\x99\xbe\xe5\xba\xa6'
# b'\xe7\x99\xbe\xe5\xba\xa6'

 (bool) Boolean type

True and False are keywords in Python. When inputting as Python code, you must pay attention to the capitalization of letters , otherwise the interpreter will report an error.

Interestingly, the boolean type can also be treated as an integer in python, that is, True is equivalent to the integer value 1, and False is equivalent to the integer value 0.

Human-computer interaction - input() function, print() function

The usage of the input() function is: str = input(tipmsg)

str represents a variable of string type, input will put the read string into str.

tipmsg means prompt information, which will be displayed on the console to tell the user what to input;

If tipmsg is not written, there will be no prompt information.

The usage of the print() function is: print (value,...,sep='',end='\n',file=sys.stdout,flush=False)

The value parameter can accept any number of variables or values ;

The print() function separates multiple variables with spaces by default, and changing the separator can be set through the sep parameter;

There will always be a newline after the output of the print() function, and the default value of the end parameter is "\n";

The file parameter specifies the output target of the print() function. The default value of the parameter is sys.stdout, which represents the system standard output, which is the screen;

The flush parameter of the print() function is used to control the output cache, and this parameter is generally kept as False;

name = '你好'
age = 8
#同时输出多个变量和字符串
print("姓名:", name, "年龄:", age)
print("姓名:", name, "年龄:", age, sep=' — ')
print(40,end="\t")
print(50)
print(60,end=" ^—^ ")
print(70)

 character


format string

A conversion specifier beginning with % formats the output of various types of data

For example: age = 3

print("Warhawk, I am %d years old!" % age )

 conversion specifier

The conversion specifier is just a placeholder, it will be replaced by the value of the following expression (requires the % sign).

%d, %i converted to a signed decimal integer

%o converts to a signed octal integer

%x, %X are converted to signed hexadecimal integers

%e is converted to a floating point number expressed in scientific notation(e lowercase)

%E is converted to a floating point number expressed in scientific notation(E uppercase)

%f, %F are converted to decimal floating point numbers

%g smart select to use %f or %e format

%G smart option to use %F or %E format

%c formatting characters and their ASCII codes

%r converts an expression to a string using the repr() function

%s converts the expression to a string using the str() function

Minimum output width 

n = 12121212
print("%10d." % n) #%10d 表示输出的整数宽度至少为10

print("%5d." % n) #%5d 表示输出的整数宽度至少为5

#对于整数和字符串,当数据的实际宽度小于指定宽度时,会在左侧以空格补齐
#当数据的实际宽度大于指定宽度时,会按照数据的实际宽度输出
url = "http://www.baidu.com"
print("%35s." % url)
print("%20s." % url)

alignment, decimal precision

- specifies left alignment

+ Indicates that the number output should always be signed; positive numbers have +, negative numbers have -.

0 means to add 0 when the width is insufficient, instead of adding spaces.

The default is right alignment, you can fill the symbol with 0 to the left

For integers, padding with 0s on the right has no effect when specifying left alignment, because this will change the value of the integer.

For decimals, the above three flags can exist at the same time.

For strings, only the - flag can be used, because the symbol has no meaning for strings, and zero padding will change the value of the string.

Decimal precision: the precision value needs to be placed after the minimum width, separated by dots. in the middle;

It is also possible not to write the minimum width, but only the precision.

m represents the minimum width , n represents the output precision , and . must exist .

For example: %m.nf %.nf

n = 123123
print("%09d" % n)# %09d 表示最小宽度为9,左边补0
print("%+9d" % n)# %+9d 表示最小宽度为9,带上符号
f = 121.8
print("%-+010f" % f)# %-+010f 表示最小宽度为10,左对齐,带上符号
s = "Hello world"
print("%-10s." % s)# %-10s 表示最小宽度为10,左对齐

f = 3.1415926
print("%8.3f" % f)# 最小宽度为8,小数点后保留3位

escape character

 The ASCII encoding assigns each character a unique number, called an encoding value.

In Python, an ASCII character can be expressed not only by its entity (that is, a real character), but also by its coded value. This way of using coded values ​​to indirectly represent characters is called escape characters.

Escape characters start with \0 or \x , start with \0 to indicate an encoded value in octal form, start with \x to indicate an encoded value in hexadecimal form, escape characters in Python can only use octal or decimal hex.

\0dd \xhh dd means an octal number, hh means a hexadecimal number.

\n Newline character, move the cursor position to the beginning of the next line

\r Carriage return, move the cursor position to the beginning of the line

\t Horizontal tab character, that is, the Tab key, generally equivalent to four spaces

\b Backspace (Backspace), move the cursor position to the previous column

\\ backslash \' single quote \" double quote

\ The continuation character at the end of the string line, that is, the line is not finished, go to the next line to continue writing

 type conversion

int(x) converts x to an integer type

float(x) converts x to a floating point type

complex(real, [, imag]) creates a complex number str(x) converts x to a string

repr(x) converts x to an expression string

eval(str) evaluates a valid Python expression in a string and returns an object

chr(x) converts the integer x to a character

ord(x) converts a character x to its corresponding integer value

hex(x) converts an integer x to a hexadecimal string

oct(x) converts an integer x to an octal string

In addition to using placeholders, the output information can also be connected with +, but the condition is that the types at both ends of + need to be consistent

height = 175.6

print("Your height: "+height) #Since height is a floating point type, it cannot be connected with a string

# You can convert the floating point type to a string


operator


 arithmetic operator

Arithmetic operators, also known as mathematical operators, are used to perform mathematical operations on numbers, such as addition, subtraction, multiplication and division.

Commonly used arithmetic operators pictures

+ The addition operator , in addition to addition, can also be used as a string concatenation

- The subtraction operator , in addition to being used as a subtraction operation, can also be used as a negative operation (positive numbers become negative numbers, negative numbers become positive numbers)

* Multiplication operator , in addition to being used as a multiplication operation, can also be used to repeat strings

/ means ordinary division , and the result calculated by using it is the same as the calculation result in mathematics.

// Indicates integer division , only keep the integer part of the result, and discard the decimal part

                                        Note that the decimal part is discarded directly, not rounded.

The % operator is used to find the remainder of dividing two numbers, including integers and decimals.

The ** operator is used to find the yth power of an x, that is, the power (power) operator.

                        Since square root is the inverse of power, it can also be implemented indirectly using the ** operator.

 bitwise operator

Python bit operations operate on the binary bits (Bit) of data in memory. Bit operators can only be used to operate on integer types, and they are calculated according to the binary form of integers in memory.

bitwise operator

 & The bitwise AND operator , the operation rule is: only when the two bits involved in the & operation are both 1, the result is 1, otherwise it is 0.

For example, 1&1 is 1, 0&0 is 0, and 1&0 is also 0, which is very similar to the logical operator &&.

The & operator operates on the raw binary bits of the data as they are stored in memory, not on the binary form of the data itself; the same goes for other bitwise operators

Take -9 as an example: 1111 1111 -- 1111 1111 -- 1111 1111 -- 1111 0111 (-9 stored in memory)

-0000 0000 -- 0000 0000 -- 0000 0000 -- 0000 1001 (binary form of -9)

|Bitwise OR operator , the operation rule is: when one of the two binary bits is 1, the result is 1, and when both are 0, the result is 0.

For example, 1|1 is 1, 0|0 is 0, and 1|0 is 1, which is very similar to || in logical operations.

^Bitwise XOR operator , the operation rule is: when the two binary bits involved in the operation are different, the result is 1, and when they are the same, the result is 0. For example 0^1 is 1, 0^0 is 0, and 1^1 is 0.

~ The bitwise inversion operator is a unary operator (only one operand), right associative, and its function is to invert the binary bits involved in the operation. For example, ~1 is 0, and ~0 is 1, which is very similar to ! in logical operations.

The << left shift operator is used to shift all the binary bits of the operand to the left by several bits, the high bits are discarded, and the low bits are filled with 0.

>>Right shift operator , which is used to shift all the binary bits of the operand to the right by several bits, discard the low bits, and fill the high bits with 0 or 1. If the highest bit of the data is 0, then add 0; if the highest bit is 1, then add 1.

 assignment operator

The assignment operator is used to pass the value on the right to the variable (or constant) on the left

You can directly pass the value on the right to the variable on the left, or you can perform some calculations and then pass it to the variable on the left

Such as addition, subtraction, multiplication and division, function calls, logical operations

Assignment operator after python extension

 comparison operator

Comparison operators, also known as relational operators , are used to compare the results of constants, variables, or expressions.

If this comparison is established, it returns True (true), otherwise it returns False (false).

comparison operator

 

== is used to compare whether the values ​​of two variables are equal, and is is used to compare whether the two variables refer to the same object

How to judge whether two objects are the same? The answer is to judge the memory addresses of the two objects. If the memory addresses are the same, it means that the two objects use the same memory, of course they are the same object

 Logical Operators

Logical Operators

 Logical operators are used to operate expressions of bool type, and the execution result is also bool type, both of which are actually wrong!

Python logical operators can be used to operate any type of expression, whether the expression is bool type or not;

At the same time, the result of logical operation is not necessarily bool type, it can also be any type.

and and or do not necessarily calculate the value of the expression on the right, and sometimes only calculate the value of the expression on the left to get the final result.

If both sides of the logical operator are numbers, the and and or operators take the value of one of the expressions as the final result, rather than True or False as the final result.

and operation:

                If the value of the expression on the left is false, then there is no need to calculate the value of the expression on the right, because no matter what the value of the expression on the right is, it will not affect the final result, and the final result is false. At this time, and will express the left formula value as the final result.

                If the value of the expression on the left is true, then the final value cannot be determined, and will continue to calculate the value of the expression on the right, and use the value of the expression on the right as the final result.

or operation:

                 If the value of the expression on the left is true, then there is no need to calculate the value of the expression on the right, because no matter what the value of the expression on the right is, it will not affect the final result, and the final result is all true. At this time, or will express the left formula value as the final result.

                If the value of the expression on the left is false, then the final value cannot be determined, or will continue to calculate the value of the expression on the right, and use the value of the expression on the right as the final result.

Ternary operator

Ternary operator (conditional operator): exp1 if contion else exp2

condition is the judgment condition, and exp1 and exp2 are two expressions.

If the condition is true (the result is true), execute exp1, and use the result of exp1 as the result of the entire expression;

If the condition is not true (the result is false), execute exp2, and use the result of exp2 as the result of the entire expression.

Priority and associativity 

Priority and associativity

The so-called associativity refers to which operator is executed first when multiple operators with the same priority appear in an expression: the left associativity is executed first, and the right associativity is executed first.

Most operators in Python are left associative, that is, executed from left to right;

The only exceptions are the exponentiation operator, the unary operator (such as the not logical negation operator), the assignment operator, and the ternary operator, which are right-associative, that is, executed from right to left.


 When you count profit, you count the world's profit; when you seek fame, you seek eternal fame


——Lungcen

Guess you like

Origin blog.csdn.net/qq_64552181/article/details/129647224