0
any one please give me answer to construct a program for counting special characters in a string
3 Réponses
+ 1
what do you mean by 'special characters'? is it some characters specified by you or it is every character that is not a digit or letter?
anyway, look at regular expressions, you can do anything like this using them
+ 1
# a generalizable solution
str_to_check="abcdef\n\tghijk"
spec_chars=set()
# add whatever you consider 'special'
for c in range(32):
spec_chars.add(chr(c))
# can use extract to see what it found
extract =(i for i in list(str_to_check) if i in spec_chars)
print(len(list(extract)))
=====
(prints '2' in this case)
0
aString = '123abcamp;!?'
letterNumcount = 0
charCount = 0
for i in aString:
if i.isalnum(): #checks for letters and numbers
letterNumcount += 1
elif not (i.isalnum() or i.isspace()):
#checks character is not a letter, number, or #space
charCount += 1
print('letter and number count: ', letterNumcount)
print('character count: ', charCount)