Python 提取字符串中第一个数字 2021-10-19

Python 提取字符串中第一个数字

#函数功能: 提取字符串中第一个数字,支持科学计数法. 如果字符串中不包含数字则返回0
def getNumFromString(sss):
	slen = len(sss)
	ret_value = 0 #返回值
	sflag = 0 #标记是否遇到第一个数字字符 0-未遇到 1-已遇到
	zflag = 1 #数字整数部分标记 默认1-整数
	pnflag = 1 #正负号标记 默认1-正数
	scientificEnumerationFlag = 0 #科学计数法标记
	cnt = 1 #小数部分长度计数
	power_num = 0 #幂
	power_pnFlag = 1
	#print("字符串长度=%s"%slen)
	for i in range(slen):
		if sss[i].isdigit():
			sflag = 1
			if scientificEnumerationFlag:
				power_num = power_num*10 + int(sss[i])
				#print("current step power_num=%s"%power_num)
			else:
				if zflag == 1:
					ret_value = ret_value*10 + int(sss[i])
					#print(ret_value)
				else:	
					divnum = 10**cnt
					ret_value = ret_value + float(sss[i])/(divnum)
					#print("div_num=%s, current step ret_value=%s"%(divnum,ret_value))
					cnt+=1
		else:
			if sflag == 1:
				if sss[i] == '.':
					zflag = 0
				elif sss[i] == 'e' and (sss[i+1] == '+' or sss[i+1] == '-'):
					scientificEnumerationFlag = 1 #开启科学计数法
					if(sss[i+1] == '+'):
						power_pnFlag = 1
					else:
						power_pnFlag = -1
					#print("幂的符号=%s"%power_pnFlag)
				else:
					if sss[i-1] == 'e' and (sss[i] == '+' or sss[i] == '-'):
						continue
					else:
						#print("-------------break------------")
						break
			else:
				if sss[i] == '-':
					pnflag = -1
	return pnflag*ret_value*(10**(power_num*power_pnFlag)) #符号*返回值*(10**(幂*幂的符号))
    原文作者:春风放胆来梳柳
    原文地址: https://blog.csdn.net/qq_15019579/article/details/120845479
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞