0

My code adds the letters together. But I only need to count the number of letters.

For example, for the input string "a12a", the output will be 2 because there are 2 letters.

def countingletters(st):
    empty = []
    for i in st:
        if i.isalpha():
            empty += str(i)

    return empty
2
  • Well, why are you using a list to count things? Commented Oct 25, 2019 at 0:47
  • my_string = 'a12a'; sum(c.isalpha() for c in my_string) Commented Oct 25, 2019 at 0:48

3 Answers 3

1

Method 1: Using a list (as you did)

def countingletters(st):
    empty = []
    for i in st:
        if i.isalpha():
             empty += str(i)

    return len(empty)

# test
print(countingletters("a12a")) # display 2

Method 2: Use a counter

def countingletters(st):
    cpt = 0 # the counter
    for i in st:
        if i.isalpha():
            cpt += 1
    return cpt


# test
print(countingletters("a12a")) # display 2

Method 3: Using a list comprehensions

def countingletters(st):
    return len([i for i in st if i.isalpha()])

# test
print(countingletters("a12a")) # display 2
Sign up to request clarification or add additional context in comments.

1 Comment

Method 4: Use a generator expression. sum(c.isalpha() for c in st)
1

it adds the letters together

Not quite... It appends letters to a list, separately, not combines all letters together

You could simply return len(empty), however maintaining a list instead of just an integer is not the optimal solution

2 Comments

If you have to count unique letters, that's a different solution
The OP's example makes it clear that aa counts as two, not one.
1

Try

def countingletters(st):
    empty = []
    for i in st:
        if i.isalpha():
             empty+= str(i)

    count_letters = len(empty)
    print(count_letters)

    return empty

Just count the len of the array with the letters. I don't know if you want to print the result but that's the answer.

2 Comments

Well, just an example, the important part is de variable count_letters = len(empty)
Not sure how this got upvoted considering it doesn't even work. TypeError: 'str' object is not callable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.