![图片[1]-python判断字符串是否为数字-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5d69dc4eacbdf494.jpg)
以下实例通过创建自定义函数is_number()方法来判断字符串是否为数字:
更多相关内容,请参考这篇文章:《python判断字符是否为字母和数字》
#-*-coding:UTF-8-*-
#Filename:test.py
#authorby:www.runoob.com
defis_number(s):
try:
float(s)
returnTrue
exceptValueError:
pass
try:
importunicodedata
unicodedata.numeric(s)
returnTrue
except(TypeError,ValueError):
pass
returnFalse
#测试字符串和数字
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
我们也可以使用内嵌 if 语句来实现:
执行以上代码输出结果为:
False True True True True True True True False
Pythonisdigit()方法检测字符串是否只由数字组成。
原文来自:https://www.py.cn© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END


















































暂无评论内容