Fork me on GitHub

随笔 - 997  文章 - 5  评论 - 181  阅读 - 300万 

最近的一个小软件,遇到了一个问题就是需要把字符串转成数字,可字符串中有时候会出来特殊字符。所以只需要做一个转换函数才可以的。下面这个函数比较凑效。这里做一个笔记本吧。

测试字符串是否是数字:

复制代码
# -*- coding: UTF-8 -*-
 
# Filename : test.py
# author by : www.runoob.com
 
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
 
    return False
 
# 测试字符串和数字
print(is_number('foo'))   # False
print(is_number('1'))     # True
print(is_number('1.3'))   # True
print(is_number('-1.37')) # True
print(is_number('1e3'))   # True
复制代码

测试字符串是否是广义的数字:

复制代码
# -*- coding: UTF-8 -*-
 
# Filename : test.py
# author by : www.runoob.com
 
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
 
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
 
    return False
 
# 测试字符串和数字
print(is_number('foo'))   # False
print(is_number('1'))     # True
print(is_number('1.3'))   # True
print(is_number('-1.37')) # True
print(is_number('1e3'))   # True
 
# 测试 Unicode
# 阿拉伯语 5
print(is_number(' '))  # True
# 泰语 2
print(is_number(''))  # True
# 中文数字
print(is_number('')) # True
# 版权号
print(is_number('©'))  # False
复制代码

 

posted on   虚生  阅读(259)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
历史上的今天:
2018-11-09 C语言那年踩过的坑--局部变量,静态变量,全局变量在内存中存放的位置
2018-11-09 RISC-V踩坑记----__builtin_clz((x)库函数的应用
点击右上角即可分享
微信分享提示