python通过自定义isnumber函数判断字符串是否为数字的方法

yipeiwu_com5年前Python基础

本文实例讲述了python通过自定义isnumber函数判断字符串是否为数字的方法。分享给大家供大家参考。具体如下:

''' isnumeric.py
test a numeric string s if it's usable
for int(s) or float(s)
'''
def isnumeric(s):
  '''returns True if string s is numeric'''
  return all(c in "0123456789.+-" for c in s)
# test module ...
if __name__ == '__main__':
  print(isnumeric('123'))   # True
  print(isnumeric('-123.45')) # True
  print(isnumeric('+3.14'))  # True
  print(isnumeric('$99.95'))  # False

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python库urllib与urllib2主要区别分析

作为一个Python菜鸟,之前一直懵懂于urllib和urllib2,以为2是1的升级版。今天看到老外写的一篇《Python: difference between urllib and...

python 计算两个列表的相关系数的实现

python 计算两个列表的相关系数的实现

用pandas计算相关系数 计算相关系数用pandas,比如我想知道风速大小与风向紊乱(标准差来衡量)之间的相关系数,下面是代码: import pandas as pd impor...

Python从文件中读取数据的方法讲解

编写了一个名为learning_python.txt的文件,内容如下: [root@centos7 tmp]# cat learning_python.txt In Python...

在Pycharm中对代码进行注释和缩进的方法详解

一、注释 1. #单行注释 2. """ 多行注释 """ 3. pycharm多行注释快捷键:Ctrl+/ 二、缩进 缩进:Tab 反向缩进:Shift+Tab 以上这篇在...

numpy实现合并多维矩阵、list的扩展方法

一、合并多个numpy矩阵 1、首先创建两个多维矩阵 矩阵a的大小为(2,3,2) 矩阵b的大小为(3,2,3) 采用concatentate这个函数就可以合并两个多维矩阵 合并之后...