Python isdigit()函数使用详解

「作者主页」:士别三日wyx
「作者简介」:CSDN top100、阿里云博客专家、华为云享专家、网络安全领域优质创作者
「推荐专栏」:小白零基础《Python入门到精通》

isdigit() 可以「判断」字符串是否只包含「数字」

语法

string.isdigit()

返回值

  • 字符串所有字符都是数字返回True
  • 否则返回False

实例:判断字符串是否只包含数字

print('123'.isdigit())

输出:

True

1、包含负数的情况

「负数」在我们的印象中是属于数字的,但 isdigit() 会把正负号当做字符串,因此不在数字范围内。

print('-1'.isdigit())
print('+1'.isdigit())
False
False

2、包含小数的情况

「小数」在我们的印象中也是属于数字的,但 isdigit() 会把小数点当做字符串,所以也不在数字范围内。

print('1.1'.isdigit())
print('0.2'.isdigit())

输出:

False
False

3、带圈的数字

「圈」的数字通常被当做字符串,但 isdigit() 会把它当做数字

print('⑴'.isdigit())
print('(1)'.isdigit())

输出:

print('⑴'.isdigit())
print('(1)'.isdigit())

这里需要注意下,数字外面的圈不是括号,中文输入法打 v2 可以输入带圈的数字。

在这里插入图片描述

4、数字上标

数字「上标」也被 isdigit() 当做数字

print('⁴'.isdigit())
print('123⁴'.isdigit())

输出:

True
True

5、bytes类型

「bytes」也是字符串的一种类型,它也可以使用 isdigit() ,并在纯数字的时候返回 True

byte1 = b'123'
print(type(byte1))
print(byte1.isdigit())
print(b'abc'.isdigit())

输出:

<class 'bytes'>
True
False

猜你喜欢

转载自blog.csdn.net/wangyuxiang946/article/details/131549783
今日推荐