
专栏目录
专栏详情
将 Dict 类型的字符转换为 Dict 对象
import ast
dict_obj = ast.literal_eval("{'key': 'value'}")
import json
json.loads("{'key': 'value'}")
将 Unicode 码转为 String 类型
unicode = u"unicode"
string = unicode.encode("unicode-escape").decode("string_excape")
将 String 类型转为 Unicode 码
string = "string"
unicode = string.decode("unicode-escape")
将 JSON 数据格式化输出
import json
json_code = {"key": "value"}
json.dumps(json_code, sort_keys=True, indent=4, separtors=(",", ":"))
删除 String 中所有的空字符
old_string = "a b c d e f"
new_string = "".join(old_string.split())
获取某变量值对应的变量名的变量值
a = "b"
b = '这个是b的变量值'
eval(a)
对 String 类型的数据格式化
"{boy_name} 还是很喜欢 {girl_name}".format(boy_name="Medusa", girl_name="medusa")
"{0} 还是很喜欢 {1}".format("Medusa", "medusa")
boy_name = "Medusa"
girl_name = "medusa"
f"{boy_name} 还是很喜欢 {girl_name}"
输出可视化日志信息,包含自定义输出格式
from logger import logger
logging.debug("debug")
logging.info("info")
logging.warning("warning")
logging.error("error")
logging.critical("crirical")
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logging.debug("debug")
logging.info("info")
logging.warning("warning")
logging.error("error")
logging.critical("crirical")
输出Python原始异常错误,并写进日志文件log.log
import traceback
try:
'需要异常捕获的代码'
except Exception:
traceback.print_exc(file=open("log.log", "a"))
偏函数的定义和使用
import functools
def func(a, b):
""" 计算传递的 a 和 b 的乘积 """
print(a * b)
new_func = functools.partial(func, 100)
new_func(2)
new_func(3)
new_func(4)
匿名函数的定义和使用
func = lambda x: x * x
map(func, [1, 2, 3, 4, 5, 6, 7, 8, 9])
对List类型数据进行数值排序
a = [5, 2, 1, 12]
a.sorted(reverse=True)
a.sort(reverse=True)
查询本地文件的相关时间信息
import os
os.path.getatime("file_path") # 指定文件路径的文件 访问时间
os.path.getctime("file_path") # 指定文件路径的文件 创建时间
os.path.getmtime("file_path") # 指定文件路径的文件 修改时间
Python的数据类型
| 类型关键字 | 举个栗子 | 枚举 | 说明 |
|---|
| str | "string" | - | 字符串类型 |
| int | 1, 2, 3 | - | 整数类型 |
| float | 1.2, 0.2 | - | 小数类型 |
| bool | True, False | True, False | 布尔类型 |
| complex | (1+0j), (2+0j) | - | 复数类型 |
| list | [1, 2, 3] | - | 列表类型 |
| set | {1, 2, 3} | - | 集合类型 |
| dict | {"key": "value"} | - | 字典类型 |
| tuple | (1, 2, 3) | - | 元组类型 |
| None | None | None | 空对象 |