编写一个 Python示例,使用 For 循环、while 循环和函数对字符串中的字母、数字和特殊字符进行计数。
这个 python 程序允许用户输入一个字符串。
首先,我们使用 For Loop 来迭代一个字符串中的字符。在 For 循环中,我们使用 Elif 语句
# 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 计数字母、数字和特殊字符的程序中,我们将每个字符与 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
标签: django基础