Column catalog

  • Converts Dict characters to Dict objects
  • Converts Unicode codes to strings
  • Convert the String type to Unicode code
  • Format the JSON data for output
  • Delete all null characters from String
  • Gets the variable value of the variable name corresponding to a variable value
  • Format String data
  • Output visual log information, including custom output formats
  • Print the original Python exception error and write it to the log file log.log
  • Definition and use of partial functions
  • Definition and use of anonymous functions
  • Sort data of type List numerically
  • Example Query time information about local files
  • Python data types

Column details

Converts Dict characters to Dict objects

import ast
dict_obj = ast.literal_eval("{'key': 'value'}")

import json
json.loads("{'key': 'value'}")
Copy the code

Converts Unicode codes to strings

unicode = u"unicode"
string = unicode.encode("unicode-escape").decode("string_excape")
Copy the code

Convert the String type to Unicode code

string = "string"
unicode = string.decode("unicode-escape")
Copy the code

Format the JSON data for output

import json
json_code = {"key": "value"}
json.dumps(json_code, sort_keys=True, indent=4, separtors=(",", ":"))
Copy the code

Delete all null characters from String

old_string = "a b c d e f"
new_string = "".join(old_string.split())
Copy the code

Gets the variable value of the variable name corresponding to a variable value

A = "b" b = 'this is the variable value of b' eval(a) # prints the result: "this is B "# This function executes a string as code and is therefore extremely unsafe in projects and is not recommendedCopy the code

Format String data

Format (boy_name="Medusa", girl_name=" Medusa") "{0} {1}". Format ("Medusa", girl_name=" Medusa") "{0} ". "Medusa") # Python3 boy_name = "medusa" girl_name = "medusa" f"{boy_name}Copy the code

Output visual log information, including custom output formats

From Logger import Logging.debug ("debug") # Most detailed log information, debug mode logging.info("info") # Next to debug log information, Warning ("warning") # This is an alarm that is generated when some event is reported, such as insufficient disk space logging. Logging. Critical ("crirical") # Critical error, Import Logging. BasicConfig (level= logging.info, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) Logging.debug ("debug") # Most detailed log information, debug mode logging.info("info") # Next to debug log information, Warning ("warning") # This is an alarm that is generated when some event is reported, such as insufficient disk space logging. Logging. Critical (" Crirical ") # Critical error indicates that the server is not running correctlyCopy the code

Print the original Python exception error and write it to the log file log.log

Import traceback try: 'except Exception: traceback.print_exc(file=open("log.log", "a"))Copy the code

Definition and use of partial functions

import functools def func(a, b): Print (a * b) print(a * b) print(a * b) print(a * b) print(a * b) print(a * b) New_func (2) = functools.partial(func, 100) 200 new_func(3) # output: 300 new_func(4) # output: 400Copy the code

Definition and use of anonymous functions

Map (func, [1, 2, 3, 4, 5, 6, 7, 8, 9]) # [1, 4, 9, 16, 25, 36, 49, 64, 81]Copy the code

Sort data of type List numerically

A = [5, 2, 1, 12] a.sorted(reverse=True) # generate a new sorted list a.sorted(reverse=True) # sort the original listCopy the code

Example Query time information about local files

Import OS os.path.getatime("file_path") # File access time os.path. getcTime ("file_path") # file creation time for file path Os.path. getmTime ("file_path") # Specifies the file path modification timeCopy the code

Python data types

Type keyword Take a chestnut The enumeration instructions
str “string” String type
int 1, 2, 3 Integer types
float 1.2, 0.2 The decimal type
bool True, False True, False Boolean type
complex (1+0j), (2+0j) The plural types
list [1, 2, 3] List the type
set {1, 2, 3} Collection types
dict {“key”: “value”} A dictionary type
tuple (1, 2, 3) A tuple type
None None None An empty object