編寫一個 Python 程序,使用 For 循環、while 循環和函數對字符串中的字母、數字和特殊字符進行計數。
使用 For 循環計算字符串中字母數字和特殊字符的 Python 程序
這個 python 程序允許用戶輸入一個字符串。
首先,我們使用 For Loop 來迭代一個字符串中的字符。在 For 循環中,我們使用 Elif 語句
- 第一個語句中的 isalpha() 是檢查字符是否是字母表。如果為真,字母值遞增。
- 第二條語句中的 isdigit() 檢查字符是否為 digit。如果為真,數字值遞增。
- 否則,特殊字符值遞增。
# Python program to Count Alphabets Digits and Special Characters in a String
string = input("Please Enter your Own String : ")
alphabets = digits = special = 0
for i in range(len(string)):
if(string[i].isalpha()):
alphabets = alphabets + 1
elif(string[i].isdigit()):
digits = digits + 1
else:
special = special + 1
print("\nTotal Number of Alphabets in this String : ", alphabets)
print("Total Number of Digits in this String : ", digits)
print("Total Number of Special Characters in this String : ", special)
Python 統計字符串輸出中的字母、數字和特殊字符
Please Enter your Own String : [[email protected]](/cdn-cgi/l/email-protection) 12 cd 1212
Total Number of Alphabets in this String : 5
Total Number of Digits in this String : 6
Total Number of Special Characters in this String : 5
Python 程序使用 While 循環計數字母數字和特殊字符
在這個 Python 計數字母、數字和特殊字符的程序中,我們將每個字符與 A、A、Z、Z、0 和 9 進行比較。根據結果,我們增加相應的值。
# Python Program to Count Alphabets Digits and Special Characters in a String
str1 = input("Please Enter your Own String : ")
alphabets = digits = special = 0
for i in range(len(str1)):
if((str1[i] >= 'a' and str1[i] <= 'z') or (str1[i] >= 'A' and str1[i] <= 'Z')):
alphabets = alphabets + 1
elif(str1[i] >= '0' and str1[i] <= '9'):
digits = digits + 1
else:
special = special + 1
print("\nTotal Number of Alphabets in this String : ", alphabets)
print("Total Number of Digits in this String : ", digits)
print("Total Number of Special Characters in this String : ", special)
使用函數計算字符串中字母數字和特殊字符的程序
在這個程序中,我們將每個字符與 ASCII 值進行比較,找出這個字符串中的字母、數字和特殊字符。
# Python Program to Count Alphabets Digits and Special Characters in a String
str1 = input("Please Enter your Own String : ")
alphabets = digits = special = 0
for i in range(len(str1)):
if(ord(str1[i]) >= 48 and ord(str1[i]) <= 57):
digits = digits + 1
elif((ord(str1[i]) >= 65 and ord(str1[i]) <= 90) or (ord(str1[i]) >= 97 and ord(str1[i]) <= 122)):
alphabets = alphabets + 1
else:
special = special + 1
print("\nTotal Number of Alphabets in this String : ", alphabets)
print("Total Number of Digits in this String : ", digits)
print("Total Number of Special Characters in this String : ", special)
Python 統計字符串輸出中的字母、數字和特殊字符
Please Enter your Own String : abcd*()[[email protected]](/cdn-cgi/l/email-protection)
Total Number of Alphabets in this String : 7
Total Number of Digits in this String : 6
Total Number of Special Characters in this String : 9
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/253364.html