isdigit()
方法是 Python 中的一个内置字符串方法,如果字符串中的所有字符都是数字,则返回 True
,否则返回 False
。它有助于检查字符串是否仅包含数字字符。
参数值
此函数不接受任何参数。返回值
Python 字符串方法中的 isdigit()
方法返回一个 bool
,即 True
或 False
。
如何在 Python 中使用 isdigit()
示例 1
如果字符串中的所有字符都是数字,则 isdigit()
方法返回 True。否则,它返回 False。
text = '12345'
result = text.isdigit()
print(result) # Output: True
示例 2
如果字符串包含任何非数字字符,则 isdigit()
方法返回 False,即使它也包含数字字符。
text = '12345a'
result = text.isdigit()
print(result) # Output: False
示例 3
isdigit()
方法不将负 数字 或浮点数视为数字。
text = '-123.45'
result = text.isdigit()
print(result) # Output: False