e媒网络

一切皆可能 e媒网络 http://www.eMay.net

博客园 首页 新随笔 联系 订阅 管理

判断字符串是否是数值的传统代码参考:

sInput=input("请输入数值[整数或小数]:")
sInput2=""
bErr=False
cSign=""
if(sInput.startswith("+")):
    sPlus=sInput.count("+")
    if(sPlus==1):
        sInput2=sInput.lstrip("+")
        cSign="+"
    else:        
        bErr=True
elif(sInput.startswith("-")):
    sSub=sInput.count("-")
    if(sSub==1):
        sInput2=sInput.lstrip("-")
        cSign="-"
    else:        
        bErr=True
else:
    sChar=sInput[0:1]
    if(sChar.isdigit()==False):        
        bErr=True
    else:
        sInput2=sInput

if(bErr):
    print("数值格式不正确.")
elif(sInput2.isdigit()):
    print("数值格式正确.")
else:
    pointNum=sInput2.count(".")
    if(pointNum==1):
        s2=sInput2.replace(".","")
        if(s2.isdigit()):
            print("数值格式正确.")
        else:
            print("数值格式不正确.")    
    else:
        print("数值格式不正确.")
if(bErr==False):
    print(cSign+sInput2)

采用正则表达式来判断字符串是否是数值的参考代码:

import re


strInput = '310.1'
strList = re.findall('^[\-\+]?\d+\.?\d+$',strInput)
print(strList)
strInput2 = 'aa310.0.1'
strList2 = re.search('[\-\+]?\d+\.?\d+',strInput2)
print(strList2.group())

strInput3 = '310.0.1'
strList3 = re.match('[\-\+]?\d+\.?\d+',strInput3)
print(strList3.group())

strInput4 = '310.13'
strList4 = re.match('^[\-\+]?\d+\.?\d+$',strInput4)

if(strList4):
    res=strList4.group()
    print(res)
else:
    print("Err")strInput5 = '310.01a'
strInput5 = '310.13'
strList5
= re.fullmatch('[\-\+]?\d+\.?\d+',strInput5) if(strList5): print(strList5.group()) else: print("Err")

posted on 2022-11-30 18:25  e媒网络技术团队  阅读(202)  评论(0编辑  收藏  举报