I"m struggling on how to count the letter, number, and special character in a string. I'm a beginner and exploring python. Thank you in advance guys!
string=input("Enter string: Abc123--- ")
count1=0
count2=0
count3=0
count4=0
for i in string:
if(i.isletter()):
count1=count1+1
count2=count2+1
count3=count3+1
count4=count2+1
print("Letter count:")
print(count1)
print("Number count:")
print(count2)
print("Special Characters count:")
print(count3)
print("Total characters count:")
print(count4)
Use function len()
to count symbols in string:
print(len(string))
Use this:
for x in string:
if type(x) is int:
num_int += 1
elif type(x) is str:
num_str += 1
else:
special_chr += 1
There are many ways you can do this. A simple approach would be:
import string
def letters(text):
letter_list = string.ascii_uppercase + string.ascii_lowercase
counter = 0
for i in text:
if i in letter_list:
counter += 1
return counter
def numbers(text):
number_list = "0123456789"
counter = 0
for i in text:
if i in number_list:
counter += 1
return counter
# you can just assume rest is the special if you have specially defined chars this works
def special(text):
letter_list = "^&*+-"
counter = 0
for i in text:
if i in letter_list:
counter += 1
return counter
def counter(text):
l = letters(text)
n = numbers(text)
s = special(text)
return {"numbers": l, "letters":l, "special":s}
print(counter("Abc123---"))
Also a more compressed version would be:
import string
def counter(text):
number_list = "0123456789"
letter_list = string.ascii_uppercase + string.ascii_lowercase
letter_count = 0
number_count = 0
special_count = 0
for i in text:
if i in number_list:
number_count += 1
elif i in letter_list:
letter_count += 1
else:
special_count += 1
return {"numbers": number_count, "letters":letter_count, "special":special_count}
print(counter("Abc123---"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.