Follow 👆 the public account and reply "python" to get a zero-based tutorial! Source from the internet, please delete if infringing.
Basic Classes
The basic and most commonly used classes in Python include int (integer), float (floating point), str (string), list (list), dict (dictionary), set (set), tuple (tuple), etc. int and float are generally used for variable assignment, while tuple is an immutable object, and operations on it are usually limited to iteration. The str, list, dict, and set are the most flexible and commonly used types in Python. Once you master the operations of these four types, you can use most of the basic types in Python flexibly.
str (String)
a.endswith('d') # Checks if string a ends with d, returns a boolean value
a.startswith('d') # Checks if string a starts with d, returns a boolean value
a.isalnum() # Checks if string a contains both numbers and letters, returns a boolean value
a.isalpha() # Checks if string a consists entirely of letters, returns a boolean value
a.isdigit() # Checks if string a consists entirely of digits, returns a boolean value
a.isspace() # Checks if string a consists entirely of spaces, returns a boolean value
a.istitle() # Checks if the first letter of string a is capitalized, returns a boolean value
a.islower() # Checks if the input string consists of lowercase letters, returns a boolean value
a.isupper()# Checks if the input string consists of uppercase letters
a.lower() # Converts uppercase letters in the string to lowercase
a.upper() # Converts lowercase letters in the string to uppercase
a.swapcase() # Reverses the case of letters
a.capitalize() # Capitalizes the first letter of the string
a.title()# Capitalizes the first letter of each word in the string separated by spaces
4) Remove Specified Elements from String
# (Removes spaces by default) (returns result string)
a.lstrip('m') # Removes elements from the left side of the string
a.rstrip('m') # Removes elements from the right side of the string
a.strip('m') # Removes elements from both sides, but not from the middle
5) Join Method
# join is used to concatenate each element of an iterable object using a specific string--->join(iterable object parameter type)
'm'.join(str) # Joins each element in the string str using m, returns a new string, the content of the original string str is unchanged
'm'.join(list) # Converts the list to a string, using m to separate each element
6) Replace Method
# replace: str.replace('a', 'b', n) # Replaces the first n occurrences of a in string st with b, defaults to replacing all matching elements if n is omitted
a = str.maketrans('abcdefg', '1234567') # Maps the first string to the second, a-->1, c-->3
'ccaegg'.translate(a) # Outputs the string result after mapping according to the above maketrans, result: 331577
# tab to space conversion
st.expandtabs(tabsize = 8) # Converts tabs in string st to spaces, default is 8
7) Search
a.find(b, 3, 10) # Finds the index of the first occurrence of b in string a from front to back, 3, 15 is the starting and ending index range, defaults to searching the entire string
a.rfind(b, 3, 10) # Finds the index of b in string a from back to front
a.index(b) # Finds the index by value from left to right
a.rindex(b) # Finds the index by value from right to left
a.count(b) # Counts how many times b appears in string a
8) Split String
# split (returns result type is list)
a.split(b) # Splits the string by b, defaults to space
a.splitlines() # Splits by newline characters, each line's content is an element of the list
# partition (returns result type is tuple)
a.partition(b) # Splits string a into three parts with the first b from left to right
a.rpartition(b) # Splits string a into three parts with the first b from right to left
9) Random Character Library string
import string
string.ascii_letters # Outputs all uppercase and lowercase letters
string.digits # Outputs all (0-9) digits
string.ascii_letters # Outputs both uppercase and lowercase letters
string.ascii_lowercase # Outputs lowercase letters
string.ascii_uppercase # Outputs uppercase letters
10) String Formatting
# format (modifiers and specifiers are the same as in C language)
"{name}huh{age}".format(name='byz', age=18) # Formats string
"{name}huh{age}".format_map({'name': 'zhangsan', 'age': 18}) # Formats dictionary
# Placeholder % (modifiers and specifiers are the same as in C language)
"%d%f%s" % (2, 3.14, "huh") # Alignment
a.center(n, b) # Total length is n, places string a in the center, filling b on both sides
a.ljust(n, b) # Total length is n, places string a on the left, filling b on the right
a.rjust(n, b) # Total length is n, places string a on the right, filling b on the left
a.zfill(n) # Total length is n, places string a on the right, filling '0' on the left
11) Encoding
str.decode(encoding[, replace]) # Encoding str
str.encode(encoding[, replace]) # Decoding str
list (List)
1) Add
list.append(obj) # Append to the end
list.insert(index, obj) # Insert obj at index
list.extend(list) # Merge list to the end
2) Delete
del list[index] # Directly delete
list.pop(index) # Delete and return the specified element
list.remove(obj) # Delete the first found obj
list.clear() # Clear the list
3) Modify
list[index] = obj # Directly modify the element at index to obj
4) Retrieve
list.index(obj) # Returns the index of the first matched obj from the left
list.count(obj) # Returns the count of obj
5) Sort
list.sort(key=<sorting rule="">, reverse=<boolean>) # An operation on the list
sorted(<iterable>, key=<sorting rule="">, reverse=<boolean>) # Returns a new sorted list
list.reverse() # Reverses</boolean></sorting></iterable></boolean></sorting>
6) Copy
list.copy() # Returns a shallow copy of the list
dict (Dictionary)
.clear() # Clears all elements in the dictionary
.copy() # Shallow copy of the dictionary
.fromkeys() # Creates a dictionary with elements of sequence seq as keys, val as the initial value for all corresponding keys
.get(key, default=None) # Sets the default value for keys not in the dictionary
key in dict # Checks if the key is in the dictionary, returns true or false
.items() # Iterates through the (key, value) tuples as a list
.keys() # Converts to a list using list()
.setdefault(key, default=None) # Adds or sets the key to default for keys not in the dictionary
.update() # Updates the keys and values in the dictionary to another dictionary
.values() # Converts to a list using list()
.pop(key[.default]) # Deletes the key's value in the dictionary, returns the deleted key's value
.popitem() # Randomly deletes a pair of key-value in the dictionary (generally deletes the last pair)
set (Set)
1) The following methods return a new set
2) The following methods operate on the original set s
Built-in Methods
The numerous built-in methods are also a characteristic that distinguishes Python from other programming languages. Mastering the use of these built-in methods can already achieve most of Python’s functionality, and flexibly using Python’s built-in methods can significantly improve code speed and reduce code volume.
Type Conversion
bool(object): returns the boolean value corresponding to object
str(object, encoding=encoding, errors=errors): returns the string corresponding to object encoded in encoding, errors is the operation when conversion fails
int(value, base=10): forces value to be converted to decimal int type. If value is a number, base cannot be changed; if it is a string, base is the value's base
float(value): converts value to a floating point number
complex(real, imaginary): returns a complex object (real + imaginary j) The first parameter can also be a string representing a complex number, omitting the second parameter
list(iterable): creates a list corresponding to iterable
tuple(iterable): returns a new tuple of the created iterable
set(iterable): returns a new set object of the iterable
dict(key1=value1, key2=value2...): creates a dictionary object
enumerate(iterable, start=0): converts iterable into an enumerate object, start: starting enumeration number, the enumerate object is an iterable object, each iteration returns (number, iterable[i])
Object and Attribute Operations
object(): returns an empty object. This object cannot have new attributes or methods added. This object is the basis of all classes, and it has all the default built-in attributes and methods of classes.
callable(object): returns True if the specified object is callable, otherwise returns False.
isinstance(object, class): returns True if object is of the specified class type, otherwise returns False. If class is a tuple, this function will return True if the object is one of the types in the tuple. isinstance() vs type(): type() does not consider class inheritance, while isinstance() does.
id(object): returns the id value of object
type(): returns a type object. Usage 1: type(object): indicates the type of object. Usage 2: type(name, bases, dict): creates a new type. name: type name, bases: tuple of base classes, dict: namespace variables defined in the class
len(object): returns the number of items in object. When the object is a string, it returns the number of characters in the string.
memoryview(obj): returns a memory view object from the specified object. A memory view object allows Python code to access data that supports the buffer protocol without needing to copy the object.
globals(): returns all global variables at the current location as a dictionary
locals(): returns local variables as a dictionary.
vars(object): returns the __dic__ attribute of object. If no parameter is provided, it is equivalent to locals().
dir(object): returns all attributes and methods of object (returns in list form)
delattr(object, attribute): deletes the attribute attribute of object, equivalent to del object.attribute
getattr(object, attr[, default]): returns the value of the attribute attr of object. default: optional parameter, the value returned if attr does not exist
hasattr(object, attribute): returns True if object has the attribute attribute, otherwise returns False
setattr(object, attribute, value): sets the value of the attribute attribute of object to value
issubclass(child, father): returns True if child is a subclass of father, otherwise returns False.
super(): Usage 1: super() -> same as super(__class__, <first argument="">) Usage 2: super(type) -> unbound super object Usage 3: super(type, obj) -> bound super object; requires isinstance(obj, type) Usage 4: super(type, type2) -> bound super object; requires issubclass(type2, type)</first>
Mathematical Operations
abs(x): returns the absolute value of x. Difference: fabs() function only applies to float and integer types, while abs() also applies to complex numbers.
round(number, ndigits=None): returns the number rounded to ndigits decimal places
bin(n): returns the binary form of integer n as a string, prefix 0b
hex(number): returns the hexadecimal form of number as a string, prefix 0x
oct(n): returns the octal form of integer n as a string, prefix 0o
divmod(x, y): returns a tuple (x // y, x % y) consisting of the quotient and remainder of x divided by y
pow(base, exp, mod=None): returns base^exp % mod
max(): (iterable,[, default=obj, key=func]): returns the maximum value in iterable. default is the object returned when iterable is empty. (v1, v2...[, key=func]): returns the maximum value among v1, v2.. key is the basis for comparison, which is the value returned when func is applied to each element.
min(): same as max(), returns the minimum value
sum(iterable, start=0): returns the sum of start and the elements in iterable
Iterator Operations
all(iterable): returns True if all items in iterable are true, otherwise returns False. If the iterable is empty, all() will also return True.
any(iterable): returns True if any item in iterable is true, otherwise returns False. If the iterable is empty, any() will return False.
iter(): returns an iterator: if there is only one parameter (iterable), it returns the corresponding iterator; if the parameters are (callable, sentinel), it calls callable each iteration until the return value is sentinel.
next(iterator[, default]): returns the next element to iterate in iterator; if the iterator ends, returns default.
frozenset(iterable): returns an immutable Frozenset object converted from iterable
filter(func, iterable): returns an iterator consisting of the parts of iterable judged to be true by func
map(function, iterable,...): returns a map object (iterable) consisting of new elements obtained by applying a function to each element in iterable
zip(iterables...): returns a zip object, which is an iterator of tuples, pairing corresponding elements from each passed iterator. If the passed iterators have different lengths, the new iterator's length will be determined by the shortest iterator. Using the * operator, tuples can be unpacked into lists.
range(start=0, stop[, step=1]): returns a range object (a sequence of numbers from start to stop, left open right closed, step length step)
slice(start, end, step): returns a slice object. The slice object is used to specify how to slice a sequence. You can specify where to start the slice and where to end it, and you can also specify step. Parameters are the same as range()
reversed(sequence): returns a reverse iterator of sequence
sorted(iterable, key=None, reverse=False): returns a list of iterable sorted by key. reverse: whether to reverse
String Operations
ascii(object): returns a readable version of any object (string, tuple, list, etc.). The ascii() function replaces all non-ascii characters with escape characters.
chr(x): returns the character with Unicode code x
format(value, format_spec=''): returns a formatted string according to format_spec, same as string.format() method
ord(c): returns the unicode encoding of character c
Byte Operations
bytearray(x, encoding, error): returns a bytearray object, converting the object to a byte array object, or creating an empty byte array object of specified size. x: source used when creating the bytearray object. If it is an integer, it creates an empty bytearray of specified size. If it is a string, the encoding parameter is needed.
encoding: encoding of the string
error: specifies how to handle encoding failures.
bytes(x, encoding, error): returns a bytes object. Converts the object to a byte object, or creates an empty byte object of specified size. Parameters are the same as bytearray. The difference between bytes() and bytearray() is that bytes() returns an immutable object, while bytearray() returns a mutable object.
Compile Input and Output
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1, *, _feature_version=-1) source: a string representing a Python module, statement, or expression. filename: for runtime error messages. mode: compilation mode. flags: which future statements affect code compilation. dont_inherit: if True, stops inheriting compilation. optimize=-1, _feature_version=-1
eval(source, globals=None, locals=None,): executes the Python expression specified by source. source: a Python expression as a string or an object returned by compile() (single expression). globals: a dictionary containing global parameters. locals: a dictionary containing local variables.
exec(source, globals=None, locals=None,): executes the Python code specified by source (can be a large block of code).
input(prompt): returns the input corresponding to the string after prompting prompt.
print(value,..., sep=' ', end='\n', file=sys.stdout, flush=False): value -- indicates the output object. When outputting multiple objects, separate them with a comma. sep -- used to separate multiple objects. end -- indicates what to end with. file -- the file object to write to (with write method). flush -- if True, the output stream will be forcibly flushed, if False, it will be cached. (print output is first cached in the buffer, then output)
File Operations
Any programming language needs to operate on the file system, and most programming languages have similar file operation methods. If you master one, you can easily handle file operations in other programming languages.
Open File
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Opens a file and returns it as a file object. file: file address mode: file open mode buffering: size of the line buffer (integer), -1 for default size encoding: encoding format when opening the file newlines: if not set, universal newlines mode works (different operating systems have different newline characters)
File Object Attributes
f.buffer
f.closed: returns True if f has been closed, otherwise returns False
f.encoding: encoding format of the file
f.errors
f.line_buffering
f.mode: file open mode
f.name: file name
f.newlines
f.write_through
File Object Operations
f.close(): used to close an opened file. A closed file cannot be read or written to, otherwise it will trigger a ValueError error. The close() method can be called multiple times. When the file object is referenced to operate another file, Python will automatically close the previous file object. Using the close() method to close files is a good habit. In some cases, due to buffering, changes made to the file may not be displayed until the file is closed.
f.detach(): separates the underlying buffer from f and returns it. After detaching the underlying buffer, f is in an unusable state.
f.fileno(): returns an integer file descriptor (file descriptor FD integer), which can be used for low-level operating system I/O operations. File descriptor: the file parameter of the open() function can accept not only string paths but also file descriptors, which are integers corresponding to files already opened by the program. The standard input uses file descriptor 0, standard output uses 1, standard error uses 2, and files opened in the program use 3, 4, 5... etc.
f.flush(): used to flush the buffer, i.e., immediately write the data in the buffer to the file while clearing the buffer, not needing to passively wait for the output buffer to write. Generally, the buffer will be automatically flushed after the file is closed, but sometimes you may need to flush it before closing, and this can be done using the flush() method.
f.isatty(): returns True if the file stream is interactive, for example: connected to a terminal device.
f.read(size): returns the specified number of bytes starting from the file's pointer position. size: optional, the number of bytes to return. Default value -1 means the entire file.
f.readable(): returns True if the file is readable, otherwise returns False.
f.readline(size): reads a line from the file, including the "\n" character. If a non-negative parameter is specified, it returns the specified number of bytes, including the "\n" character. size: optional, the number of bytes to return from the line. Default value -1 means the whole line.
f.readlines(sizehint): returns a list, with each line in the file as an element of the list. sizehint: optional, sizehint is the number of bytes read from the file; if the returned number of bytes exceeds sizehint, no more lines will be returned. Default is -1, meaning all lines will be returned.
f.reconfigure(encoding=None, errors=None, newline=None, line_buffering=None, write_through=None) : reconfigures the text stream using new parameters. This will also perform an implicit stream flush.
f.seek(offset): sets the current file position in the file stream and returns that position. If the operation is successful, it returns the new file position; if the operation fails, the function returns -1. offset: required parameter, representing the number of bytes to move the offset.
f.seekable(): returns True if the file is seekable, otherwise returns False. If the file allows access to the file stream, then the file is seekable.
f.tell(): returns the current file position in the file stream.
f.truncate(size=None): adjusts the file size to the given number of bytes. If size is not specified, the current position will be used.
size: optional, size of the file after truncation (in bytes)
f.write(str): writes the specified text str to the file. Returns the size of the written text. The position where the specified text will be inserted depends on the file mode and stream position. The content of the string is stored in the buffer before the file is closed or the buffer is flushed, so you cannot see the written content in the file at this time. If the file open mode includes b, then when writing content to the file, the str (parameter) must be converted to bytes using the encode method, otherwise an error will occur.
f.writable(): returns True if the file is writable, otherwise returns False.
f.writelines(list): writes the elements of the list list to the file. The position where the text will be inserted depends on the file mode and stream position. Newlines need to be specified with the newline character \n.
How to get:
-
Like + See Again
-
Reply in the public account:“python”
Receive the latest Python zero-based learning materials for 2024,Reply in the background:Python