用一个实例编写一个 Python示例来检查字符是不是数字。
这个 python 程序允许用户输入任何字符。接下来,我们使用 If Else 语句来检查用户给定的字符是否是数字。这里, If 语句检查字符是否大于等于 0,小于等于 9。如果为真,则为数字。否则,它不是一个数字。
# Python Program to check character is Digit or not
ch = input("Please Enter Your Own Character : ")
if(ch >= '0' and ch <= '9'):
print("The Given Character ", ch, "is a Digit")
else:
print("The Given Character ", ch, "is Not a Digit")
Python 字符是数字还是不输出
Please Enter Your Own Character : 1
The Given Character 1 is a Digit
>>>
Please Enter Your Own Character : i
The Given Character i is Not a Digit
在本 Python 示例中,我们使用 ASCII 值来检查字符是否为数字。
# Python Program to check character is Digit or not
ch = input("Please Enter Your Own Character : ")
if(ord(ch) >= 48 and ord(ch) <= 57):
print("The Given Character ", ch, "is a Digit")
else:
print("The Given Character ", ch, "is Not a Digit")
Please Enter Your Own Character : 7
The Given Character 7 is a Digit
>>>
Please Enter Your Own Character : @
The Given Character @ is Not a Digit
在本例 python 代码中,我们使用 If Else 语句中的 isdigit 字符串函数来检查给定字符是否为数字。
# Python Program to check character is Digit or not
ch = input("Please Enter Your Own Character : ")
if(ch.isdigit()):
print("The Given Character ", ch, "is a Digit")
else:
print("The Given Character ", ch, "is Not a Digit")
标签: python报错