1. Enter a line of characters to count the number of English letters, spaces, numbers and other characters.
Method 1: Use regular expressions
import re
str1 = input("Please enter a line of string:")
alpha = 0 #English alphabet
space = 0 #space
digit = 0 #number
other = 0 #Other
for i in str1:
# print(i)
if (r"[A-Za-z]",i):
alpha += 1
elif (r"\s", i):
space += 1
elif (r"\d",i):
digit += 1
else:
other += 1
print(f"{str1} The number of English letters is: {alpha}")
print(f"{str1}' number of spaces: { space}")
print(f"{str1}' number of numbers: {digit}")
print(f"{str1}'s number of other characters is: {other}")
Method 2:
While True:
str1 = input("Please enter a line of string:")
alpha = 0 #English alphabet
space = 0 #space
digit = 0 #number
other = 0 #Other
for i in str1:
if ():
alpha += 1
elif ():
space += 1
elif ():
digit += 1
else:
other += 1
print(f"{str1} The number of English letters is: {alpha}")
print(f"{str1}' number of spaces: { space}")
print(f"{str1}' number of numbers: {digit}")
print(f"{str1}'s number of other characters is: {other}")
Method 3: Use list[]
While True:
str1 = input("Please enter a line of string:")
alpha = [] #English alphabet
space = [] #space
digit = [] #number
other = [] #Other
for i in str1:
if ():
(i)
elif ():
(i)
elif ():
(i)
else:
other += 1
The number of English letters in print(f"{str1} is: {len(alpha)}")
print(f"{str1} has the number of spaces: {len(space)}")
print(f"{str1} number of numbers: {len(digit)}")
print(f"{str1}'s number of other characters is: {len(other)}")