[Python] Common functions and usage in Python

enter

input() : Waiting for user input from the keyboard, anything that the user enters is considered a string by Python .

string = input("请输入任何内容:")

output

% : Formatting operator , dedicated to handling formats in strings.
A string containing % is called a format string .
Different types of data require different formatting characters.

formatting characters meaning
%s string
%d Signed decimal integer, %06d means that the output integer displays 6 digits, use 0 to complete the insufficient place
%f Floating point number, %.2f means only two digits are displayed after the decimal point
%% output %
print("格式化字符串" % 变量1)

print("格式化字符串" % (变量1, 变量2...))

type conversion

int(x [,base]) : Convert x to an integer.
long(x [,base] ) : Convert x to a long integer.
float(x) : Convert x to a floating point number.
complex(real [,imag]) : Create a complex number.
str(x) : Convert the object x to a string.
repr(x) : Convert the object x to an expression string.
eval(str) : Used to evaluate valid Python expressions in the string str and return an object.
tuple(s) : Convert the sequence s to a tuple.
list(s) : Convert the sequence s to a list.
set(s) : converts to a mutable set.
frozenset(s) : convert to an immutable set.
dict(d) : Create a dictionary where d must be a sequence of (key,value) tuples.
chr() : Convert an integer to a character.
unichr() : Convert an integer to a Unicode character.
ord() : Converts a character to its integer value.
hex() : Converts an integer to a hexadecimal string.
oct(): Convert an integer to an octal string.

quote

id() : View the memory address where the data is saved in the variable.

hash

hash(o) : returns an integer as the characteristic code (fingerprint) of o , where o is data of immutable type (numeric variable, string or tuple).
The same content gets the same result.
Different content gets different results.

string

Common operations

len(str) : Get the length of the string str.
str1.count(str2) : The number of occurrences of the substring (str2) in the parent string (str1).
str1.index(str2) : Get the index of the first occurrence of the substring (str2) in the parent string (str1).

judgment type

str.isspace() : Return True if the string contains only spaces.
str.isalnum() : Return True if string has at least one character and all characters are letters or numbers.
str.isalpha() : Returns True if string has at least one character and all characters are letters.
str.isdecimal() : Return True if the string contains only numbers, full-width numbers.
str.isdigit() : Return True if the string contains only digits, full-width digits, ⑴, \u00b2.
str.isnumeric() : Return True if the string contains only numbers, full-width numbers, and Chinese characters.
str.istitle() : Returns True if string is titled (the first letter of each word is capitalized).
str.islower() : Returns True if string contains at least one case-sensitive character and all of those (case-sensitive) characters are lowercase.
str.isupper() : Returns True if string contains at least one case-sensitive character, and all such (case-sensitive) characters are uppercase.

find replace

str.startswith(str) : Check whether the string starts with str, and return True if so.
str.endswith(str) : Check if the string ends with str, and return True if so.
str.find(str, start=0, end=len(string)): Check whether str is included in the string, if start and end specify the range, check whether it is included in the specified range, if it returns the starting index value, Otherwise -1 is returned.
str.rfind(str, start=0, end=len(string)) : similar to find(), but starts searching from the right.
str.index(str, start=0, end=len(string)) : Similar to the find() method, but if str is not in string, an error will be reported.
str.rindex(str, start=0, end=len(string)) : Similar to index(), but starts from the right.
str.replace(old_str, new_str, num=string.count(old)) : Replace old_str in string with new_str. If num is specified, the replacement will not exceed num times.

case conversion

str.capitalize() : Capitalize the first character of the string.
str.title() : Capitalize the first letter of each word in the string.
str.lower() : Convert all uppercase characters in string to lowercase.
str.upper() : Convert lowercase letters in string to uppercase.
str.swapcase() : Flips the case in string.

text alignment

str.ljust(width) : Returns a new string with the original string left justified and padded with spaces to the length width.
str.rjust(width) : Returns a new string that is right-justified from the original string and padded with spaces to a length of width.
str.center(width) : Returns a new string with the original string centered and padded with spaces to a length width.

remove whitespace

str.lstrip() : Cut off the blank characters on the left (beginning) of the string.
str.rstrip() : Cut off the blank characters on the right (end) of the string.
str.strip() : Cut off the blank characters on the left and right sides of the string.

split and join

str.partition(str) : Divide the string string into a 3-element tuple (str before, str, after str).
str.rpartition(str) : Similar to the partition() method, but starts searching from the right.
str.split(str="", num) : Split the string with str as the delimiter. If num has a specified value, only num + 1 substrings will be separated. By default, str contains '\r', '\t', '\n' and spaces.
str.splitlines() : Split by lines ('\r', '\n', '\r\n'), return a list containing each line as an element.
str.join(seq) : With string as a delimiter, combine all elements (string representations) in seq into a new string.

the list

Common operations

list.index(n) : Get the index of the first occurrence of data n in the list.

CRUD

increase

list.insert(index, data) : Insert data at the specified position.
list.append(data) : Append data at the end of the list.
list1.extend(list2) : Append the data of list2 to list1.
list.copy() : Copy the list list.

delete

del list[index] : delete the data of the specified index.
list.remove[data] : Delete the first occurrence of the specified data.
list.pop() : Delete the end data.
list.pop(index) : delete the specified index data.
list.clear() : Clear the list.

change

list[index] = data : modify the data of the specified index.

statistics

len(list) : Count the length of the list, that is, the number of elements in it.
list.count(data) : counts the number of times the data appears in the list.

to sort

list.sort() : Sort in ascending order.
list.sort(reverse=True) : Sort in descending order.
list.reverse() : reverse order, reverse.

tuple

Common operations

len(tuple) : Get the length of tuple.
tuple.count(data) : Get the number of times data appears in the tuple.
tuple.index(n) : Get the index of the first occurrence of data n in the tuple.

dictionary

Common operations

len(dic) : Get the number of key-value pairs of the dictionary dic.
dic.keys() : Obtain a list of all keys in the dictionary dic.
dic.values() : Obtain a list of all values ​​in the dictionary dic.
dic.items() : Obtain a list of all (key, value) tuples in the dictionary dic.
dic[key] : Values ​​can be obtained from the dictionary, and an error will be reported if the key does not exist .
dic.get(key) : Values ​​can be obtained from the dictionary, and no error will be reported if the key does not exist .

dic[key] = value : If the key exists, modify the data; if the key does not exist, create a new key-value pair.
dic.setdefault(key, value) : If the key exists, the data will not be modified; if the key does not exist, create a new key-value pair.
dic1.update(dic2) : Merge the data of dic2 into dic1.

del dic[key] : Delete the specified key-value pair, if the key does not exist, an error will be reported .
dic.pop(key) : Delete the specified key-value pair, if the key does not exist, an error will be reported .
dic.popitem() : Randomly delete a key-value pair.
dic.clear() : Clear the dictionary.

scope

range(stop) : Returns the number within the given range. Counting starts at 0 and ends at stop, but not including stop.
range(start, stop[, step]) : returns a number in the given range. The count starts from start (the default is from 0), and the count ends at stop, but not including stop, and step is the step size, which is 1 by default.

random

import random #导入随机数random模块包

random.random() : Returns a randomly generated real number within the semi-open interval [0,1).
random.randint(a, b) : returns an integer between [a, b], including a and b.
random.randrange([start,] stop[, step]) : The method returns a random number within the specified range. Among them, start is optional (starting from 0 by default), stop is required, but stop is not included, step is optional, and the step size is 1 by default.
random.shuffle(list) : Randomly sort all elements in the list list.
random.choice(seq) : Randomly select an element from the elements of the sequence, such as random.choice(range(10)), randomly select an integer from 0 to 9.
uniform(x, y) : Randomly generate a real number, which is in the range [x, y].
seed([x]) : Change the seed of the random number generator.

random.randint(12, 20)  # 生成的随机数n(12 <= n <= 20)
random.randint(20, 20)  # 结果总是 20   
random.randint(20, 10)  # 报错,下限必须小于上限

math

Some functions need to import the math module:

import math

Compare

max(item) : Returns the maximum value of the elements in the container. If it is a dictionary, only for key comparison.
min(item) : Returns the minimum value of the element in the container. If it is a dictionary, only for key comparison.

Common functions

abs(x) : Returns the absolute value of a number, such as abs(-10), returns 10.
math.ceil(x) : Returns the upper integer of the number, such as math.ceil(4.1), returns 5.
math.exp(x) : returns e to the power of x (ex), such as math.exp(1), returns 2.718281828459045.
math.fabs(x) : Returns the absolute value of a number in the form of a floating point number, such as math.fabs(-10), returns 10.0.
math.floor(x) : Returns the rounded integer of the number, such as math.floor(4.9), returns 4.
math.log(x) : Calculate the log value. 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 with base 10, such as math.log10(100) returns 2.0.
max(x1, x2,…) : Returns the maximum value of the given arguments, which can be sequences.
min(x1, x2,…) : Returns the minimum value of the given arguments, which can be sequences.
math.modf(x) : Returns the integer part and fractional part of x. The numerical symbols of the two parts are the same as x, and the integer part is expressed in floating point.
math.sqrt(x) : Returns the square root of the number x.
pow(x, y) : returns the value after x**y operation.
round(x[,n]): Returns the rounded value of the floating-point number x. If n is given, it represents the number of digits rounded to the decimal point. More precisely, the reserved value will be reserved to the end closer to the previous digit.

Trigonometric functions

math.acos(x) : Returns the arccosine of x in radians.
math.asin(x) : Returns the arcsine of x in radians.
math.atan(x) : Returns the arc tangent of x in radians.
math.atan2(y, x) : Returns the arctangent of the given X and Y coordinates.
math.cos(x) : Returns the cosine of x in radians.
math.hypot(x, y) : Returns the Euclidean norm sqrt(x x + y y).
math.sin(x) : Returns the sine of x in radians.
math.tan(x) : Returns the tangent of x in radians.
math.degrees(x) : Convert radians to angles, such as degrees(math.pi/2), returns 90.0.
math.radians(x) : Convert angles to radians.

mathematical constant

math.pi : Mathematical constant pi (pi, generally represented by π).
math.e : Mathematical constant e, e is the natural constant (natural constant).

おすすめ

転載: blog.csdn.net/qq_41084756/article/details/132394568