今天爱分享给大家带来Python如何判断一个字符串是否全为数字?【面试题详解】,希望能够帮助到大家。
可以有以下几种办法来判断:
(1) Python isdigit() 方法检测字符串是否只由数字组成。
(2) Python isnumeric() 方法检测字符串是否只由数字组成。这种方法只针对 Unicode 字符串。如果想要定义一个字符串为 Unicode,那么只需要在字符串前添加 u 前缀即可。
(3) 自定义函数 is_number 来判断。
# -*- coding: UTF-8 -*-
"""
@author:AmoXiang
@file:3.判断一个字符串是否全为数字.py
@time:2020/11/10
"""
def is_number(s):
try:
float(s) # 如果能运行float(s)语句,返回True(字符串s是浮点数、整数)
return True
except ValueError:
pass
try:
import unicodedata # 处理ASCii码的包
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