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

yipeiwu_com6年前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使用telnet实现弱密码登录的方法详解

系统环境: 64位win7企业版 python2.7.10 2016.08.16修改内容: 1)read_until()函数是可以设置timeout的,之前不能获取到password之后...

python+Django实现防止SQL注入的办法

先看看那种容易被注入的SQL id = 11001 sql = """ SELECT id, name, age FRO...

通过python顺序修改文件名字的方法

通过python顺序修改文件名字的方法

问题:将文件夹a下任意命名的10个文件修改为如下图所示文件? 代码: #coding:utf-8 import os path = "./a/" dirs = os.listdir...

Python新手实现2048小游戏

Python新手实现2048小游戏

接触 Python 不久,看到很多人写2048,自己也捣鼓了一个,主要是熟悉Python语法。 程序使用Python3 写的,代码150行左右,基于控制台,方向键使用输入字符模拟。 演示...

PyTorch和Keras计算模型参数的例子

Pytorch中,变量参数,用numel得到参数数目,累加 def get_parameter_number(net): total_num = sum(p.numel() fo...