Search code examples
pythonarraysspecial-characters

Counting the special character and character in an array and giving the sum of the numbers in an array


ar=input("Enter the elements:").split()
sum=0
cr=0

for i in range(len(ar)):
    if(not ar[i].isalpha()):
        a=int(ar[i])
        sum=sum+a
    else:
         cr=cr+1
print("Sum of the elements is :",sum)
print(" No of Characters in the array:",cr)

        

I can count the character but idk what to do for special characters

To count the Special charcter and give the sum


Solution

  • You check if it's neither alpha niether numeric:

    ar=input("Enter the elements:")
    char_count = 0
    special_char_count = 0
    
    for char in ar:
        if char.isalpha():
            char_count += 1
            continue
        
        if not char.isnumeric():
            special_char_count += 1
        
    print("Sum of alpha: ", char_count)
    print("Sum of special charachters: ", special_char_count)
    
    # Input: abc&--
    # Output: Sum of alphabet:  3
    #         Sum of special charachters:  3