- 语法
str.isdigit() - 参数
无 - 返回值
如果字符串只包含数字则返回 True 否则返回 False。
含有小数点,返回False
a=‘121243.23’
a.isdigit()
Out[8]: False
含有空格,返回False
b=’ 788’
b.isdigit()
Out[10]: False
全部为数字,返回True
c=‘908989’
c.isdigit()
Out[8]: True
所以直接使用str.isdigit()函数只能判断输入是否全部为数字。
如果想要判断是否为浮点数,需要用到str.replace()方法
语法:
str.replace(old, new[, max])
参数:
old – 将被替换的子字符串。
new – 新字符串,用于替换old子字符串。
max – 可选字符串, 替换不超过 max 次。
示例:
left_number_str = input(‘请输入第一个数值:’).strip() # 去除两边空格
if not left_number_str.isdigit() and not left_number_str.replace(’.’, ‘’, 1).isdigit(): #判断左边输入是否为数字,小数和整数均可
print(‘输入错误,请输入数字!’)
result = None
print(‘计算结果为{}’.format(result))