寫一個 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")
原創文章,作者:O4OVT,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/127892.html