Python程序:计算字符串中的字母、数字和特殊字符

编写一个Python程序,使用For循环、while循环和函数(带示例)来计算字符串中的字母、数字和特殊字符。

Python程序:使用For循环计算字符串中的字母、数字和特殊字符

此Python程序允许用户输入一个字符串。

首先,我们使用For循环来迭代字符串中的字符。在For循环内部,我们使用Elif语句

  • 第一个语句中的isalpha()用于检查字符是否为字母。如果为真,则字母计数器递增。
  • 第二个语句中的isdigit()用于检查字符是否为数字。如果为真,则数字计数器递增。
  • 否则,特殊字符计数器递增。
# 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 : abc!@ 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)
Python Program to Count Alphabets Digits and Special Characters in a String 2

程序:使用函数计算字符串中的字母、数字和特殊字符

在此程序中,我们将每个字符与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*()_+12211!!!@sid4

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