需求: 在数据处理时有千分位字符串需要转换成小数再进行计算和存储。
直接步入正题,上代码(具体解析看代码注释):
def thousands2float(
thousands_str
):
'''千分位字符串转Float类型
Args:
thousands_str: 千分位符串
Returns:
float: 返回浮点型数字
'''
# 首先判断是否是字符串,不是则不需要处理
if type(thousands_str) != str:
return thousands_str
# 引入re包,匹配正则表达式
import re
# 去掉字符串收尾多余空格
thousands_str_new = thousands_str.strip()
# 通过正则验证是否是千分位字符串,包含正负千分位字符串
if re.match('^\-?[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?$', thousands_str_new):
# 是千分位去掉逗号转换成float即可
return float(thousands_str_new.replace(',', ''))
else:
return thousands_str
在正则表达式验证参考了文章:Python 正则表达式验证有千位分隔符的数字
具体可访问此链接查看,https://blog.csdn.net/guaguastd/article/details/39226447
但是博主的正则没有判断负值的千分位字符串,所以在原有基础上增加\-?
负号验证修改为:
'^\-?[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?$'
如有疑问请评论或私信哈!