python变量类型格式化,结果补全值
来源:互联网 发布:mac自带快捷键怎么设置 编辑:程序博客网 时间:2024/05/19 09:10
在python对数据进行存储的时候,经常会遇到类型的错误,或者缺少某字段存储是吧。就随手写了一个简单的工具类
1,判断值是否是int
# 通过抛出异常def is_int_by_except(value): value = str(value) try: int(value) return True except ValueError: # print "%s ValueError" % value return False我是通过最常见的异常做处理
2,判断值是否是float
def is_float_by_except(string): str1 = str(string) if str1.count('.') != 1: # 判断小数点是不是大于1 return False elif str1.isdigit(): return False # 判断是不是整数 else: new_str = str1.split('.') # 按小数点分割字符 frist_num = new_str[0] # 取分割完之后这个list的第一个元素 if frist_num.count('-') > 1: # 判断负号的格数,如果大于1就是非法的 return False else: frist_num = frist_num.replace('-', '') # 把负号替换成空 if frist_num.isdigit() and new_str[1].isdigit(): # 如果小数点两边都是整数的话,那么就是一个小数 return True else: return False判断是否是float的方法有很多,只要能实现都可以
3,然后就是调用方法check值的类型
def check_result_type(result): """ 检查存储结果的类型 :param result: 需要格式化的结果 :return: """ if is_int_by_except(result): return int(result) elif is_float_by_except(result): return float(result) else: return result其实很简单不是嘛,调用一下就可以了
4,然后就是数据的补全并赋值“0”
def format_result(result, rows): """ 格式化补全结果 :param result:结果 :param rows: 行 :return: 格式化后的结果 """ for row in rows.keys(): if row in result.keys(): result[row] = check_result_type(result[row]) else: if rows.get(row) == "int": result[row] = 0 elif rows.get(row) == "float": result[row] = 0.00 else: result[row] = "0" return resultpython写起来很舒服。
5,写个main方法库测试一下
class CheckResultType(object): def __init__(self): self.result = {"id": "2333", "name": "张三", "value": 1111, "type": 9, "keyword_task_id": 3222.0} def format_result(self): types = {"id": "int", "name": "string", "value": "float", "type": "int", "keyword_task_id": "int", "class": "int"} print format_result(self.result, types)if __name__ == '__main__': CheckResultType().format_result()
简单直接。
阅读全文
0 0
- python变量类型格式化,结果补全值
- Python----变量的格式化
- 变量类型-python笔记
- python 判断变量类型
- Python 变量类型
- Python 判断变量类型
- Python 变量类型
- python变量类型
- Python判断变量类型
- Python变量和类型
- Python变量类型
- Python变量类型
- Python 变量类型
- python变量类型
- Python变量类型
- Python 变量类型
- python判断变量类型
- Python 变量类型
- tomcat中文编码相关
- CSS特殊样式(八)The Shapes of CSS
- javascript的字符串
- js判断是不是整数
- WebView设置透明背景
- python变量类型格式化,结果补全值
- 【leetcode】18.4sum 总结
- .gitignore
- RecyclerView使用介绍
- OpenCv 中Otsu 算法实现
- c/c++ 双向链表 创建 插入 删除
- MySQL中的变量定义及区别
- 界面加载动画(一帧一帧的图片组成的动画)
- MD5 encoding