首页 > 编程知识 正文

Python 程序:检查字符是字母还是数字

时间:2023-11-24 15:33:39 阅读:308856 作者:LBKQ

写一个 Python 程序,用一个实例来检查字符是字母还是数字。

Python 程序检查字符是字母还是数字

这个 python 程序允许用户输入任何字符。接下来,我们使用 Elif 语句来检查用户给定的字符是字母还是数字。

  • 这里 If 语句检查字符是在 A 和 Z 之间还是在 A 和 Z 之间,如果是 TRUE,则是字母表。否则,它进入 elif 语句。
  • 在 Elif 语句中,我们正在检查给定的字符是否在 0 到 9 之间。如果是真的,就是一个数字;否则,它不是数字或字母。
# Python Program to check character is Alphabet or Digit
ch = input("Please Enter Your Own Character : ")

if((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')): 
    print("The Given Character ", ch, "is an Alphabet") 
elif(ch >= '0' and ch <= '9'):
    print("The Given Character ", ch, "is a Digit")
else:
    print("The Given Character ", ch, "is Not an Alphabet or a Digit")

Python 字符是字母或数字输出

Please Enter Your Own Character : j
The Given Character  j is an Alphabet
>>> 
Please Enter Your Own Character : 6
The Given Character  6 is a Digit
>>> 
Please Enter Your Own Character : .
The Given Character  . is Not an Alphabet or a Digit

使用 ASCII 值验证字符是字母还是数字的 Python 程序

在这个 Python 代码中,我们使用 ASCII 值来检查字符是字母还是数字。

# Python Program to check character is Alphabet or Digit
ch = input("Please Enter Your Own Character : ")

if(ord(ch) >= 48 and ord(ch) <= 57): 
    print("The Given Character ", ch, "is a Digit") 
elif((ord(ch) >= 65 and ord(ch) <= 90) or (ord(ch) >= 97 and ord(ch) <= 122)):
    print("The Given Character ", ch, "is an Alphabet")
else:
    print("The Given Character ", ch, "is Not an Alphabet or a Digit")
Please Enter Your Own Character : q
The Given Character  q is an Alphabet
>>> 
Please Enter Your Own Character : ?
The Given Character  ? is Not an Alphabet or a Digit
>>> 
Please Enter Your Own Character : 6
The Given Character  6 is a Digit

Python 程序使用 isalpha,isdigit 函数查找字符是字母还是数字

在这个例子 python 代码中,我们使用名为 isdigit 和 isalpha 的字符串函数来检查给定的字符是字母还是数字。

# Python Program to check character is Alphabet or Digit
ch = input("Please Enter Your Own Character : ")

if(ch.isdigit()):
    print("The Given Character ", ch, "is a Digit")
elif(ch.isalpha()):
    print("The Given Character ", ch, "is an Alphabet")
else:
    print("The Given Character ", ch, "is Not an Alphabet or a Digit")

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。