如何使用 Python 的 isdigit() 方法检查字符串中的数字

2023-03-19 00:00:00 字符串 检查 如何使用

可以使用 Python 的 isdigit() 方法检查字符串中是否只包含数字字符。可以通过遍历字符串中的每个字符并检查其是否为数字字符来实现。

例如,检查字符串 "https://pidancode.com/" 中的数字字符可以使用如下代码:

string = "https://pidancode.com/"
for char in string:
    if char.isdigit():
        print(char, "is a digit.")
    else:
        print(char, "is not a digit.")

这将输出:

h is not a digit.
t is not a digit.
t is not a digit.
p is not a digit.
s is not a digit.
: is not a digit.
/ is not a digit.
/ is not a digit.
p is not a digit.
i is not a digit.
d is not a digit.
a is not a digit.
n is not a digit.
c is not a digit.
o is not a digit.
d is not a digit.
e is not a digit.
. is not a digit.
c is not a digit.
o is not a digit.
m is not a digit.
/ is not a digit.

可以看到,该字符串中并没有数字字符,因此所有字符都被判断为不是数字字符。

再例如,检查字符串 "12345" 中的数字字符可以使用如下代码:

string = "12345"
for char in string:
    if char.isdigit():
        print(char, "is a digit.")
    else:
        print(char, "is not a digit.")

这将输出:

1 is a digit.
2 is a digit.
3 is a digit.
4 is a digit.
5 is a digit.

可以看到,该字符串中的所有字符都被判断为数字字符。

相关文章