Python判断字符串是否为字母或者数字(浮点数)的多种方法

yipeiwu_com6年前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

第一种:最简单

def is_number(str):
  try:
    # 因为使用float有一个例外是'NaN'
    if str=='NaN':
      return False
    float(str)
    return True
  except ValueError:
    return False
float例外示例
 >>> float('NaN')
 nan

使用complex()

def is_number(s):
  try:
    complex(s) # for int, long, float and complex
  except ValueError:
    return False
  return True

综合1

def is_number(s):
  try:
    float(s) # for int, long and float
  except ValueError:
    try:
      complex(s) # for complex
    except ValueError:
      return False
  return True

综合2-还是无法完全识别

def is_number(n):
  is_number = True
  try:
    num = float(n)
    # 检查 "nan" 
    is_number = num == num  # 或者使用 `math.isnan(num)`
  except ValueError:
    is_number = False
  return is_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"
>>> print str.isdigit()
True
>>> str = "3.14"
>>> print str.isdigit()
False
>>> str = "aaa"
>>> print str.isdigit()
False

使用int()

def is_int(str):
  try:
    int(str)
    return True
  except ValueError:
    return False

第三种:使用正则(最安全方法)

import re
def is_number(num):
  pattern = re.compile(r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$')
  result = pattern.match(num)
  if result:
    return True
  else:
    return False
>>>: 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判断字符串是否为字母或者数字(浮点数)的多种方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

Python中dict和set的用法讲解

Python中dict和set的用法讲解

dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 举个例子,假设要...

使用PDB简单调试Python程序简明指南

使用PDB简单调试Python程序简明指南

在 Python 中也可以像 gcc/gdb 那样调试程序,只要在运行 Python 程序时引入 pdb 模块(假设要调试的程序名为 d.py): 复制代码 代码如下: $ vi d.p...

python kafka 多线程消费者&手动提交实例

官方文档:https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html import threadi...

Python修改MP3文件的方法

本文实例讲述了Python修改MP3文件的方法。分享给大家供大家参考。具体如下: 用这个程序修改后的MP3比原来要小一些了,因为一张图片被删除了,起到了给MP3"瘦身"的作用。在一些mp...

Python编程中NotImplementedError的使用方法

Python编程中raise可以实现报出错误的功能,而报错的条件可以由程序员自己去定制。在面向对象编程中,可以先预留一个方法接口不实现,在其子类中实现。 如果要求其子类一定要实现,不实现...