Python判断字符串是否为字母或者数字(浮点数)的多种方法
str为字符串s为字符串
str.isalnum()所有字符都是数字或者字母
str.isalpha()所有字符都是字母
str.isdigit()所有字符都是数字
str.isspace()所有字符都是空白字符、t、n、r
检查字符串是数字/浮点数方法
float部分
>>float('Nan')
nan
>>float('Nan')
nan
>>float('nan')
nan
>>float('INF')
inf
>>float('inf')
inf
>>float('-INF')
inf
>>float('-inf')
inf
第一种:最简单
defis_number(str):
try:
#因为使用float有一个例外是'NaN'
ifstr=='NaN':
returnFalse
float(str)
returnTrue
exceptValueError:
returnFalse
float例外示例
>>>float('NaN')
nan
使用complex()
defis_number(s): try: complex(s)#forint,long,floatandcomplex exceptValueError: returnFalse returnTrue
综合1
defis_number(s): try: float(s)#forint,longandfloat exceptValueError: try: complex(s)#forcomplex exceptValueError: returnFalse returnTrue
综合2-还是无法完全识别
defis_number(n):
is_number=True
try:
num=float(n)
#检查"nan"
is_number=num==num#或者使用`math.isnan(num)`
exceptValueError:
is_number=False
returnis_number
>>>is_number('Nan')
False
>>>is_number('nan')
False
>>>is_number('123')
True
>>>is_number('-123')
True
>>>is_number('-1.12')
True
>>>is_number('abc')
False
>>>is_number('inf')
True
第二种:只能判断是整数
使用isnumeric()
#str必须是uniconde模式 >>>str=u"345" >>>str.isnumeric()True http://www.tutorialspoint.com/python/string_isnumeric.htm http://docs.python.org/2/howt...
使用isdigit()
https://docs.python.org/2/lib... >>>str="11" >>>printstr.isdigit() True >>>str="3.14" >>>printstr.isdigit() False >>>str="aaa" >>>printstr.isdigit() False
使用int()
defis_int(str): try: int(str) returnTrue exceptValueError: returnFalse
第三种:使用正则(最安全方法)
importre
defis_number(num):
pattern=re.compile(r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$')
result=pattern.match(num)
ifresult:
returnTrue
else:
returnFalse
>>>:is_number('1')
True
>>>:is_number('111')
True
>>>:is_number('11.1')
True
>>>:is_number('-11.1')
True
>>>:is_number('inf')
False
>>>:is_number('-inf')
False
总结
以上所述是小编给大家介绍的Python判断字符串是否为字母或者数字(浮点数)的多种方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。