0

I just started learning python, and I can think of two ways to count letters in a string (ignoring numbers, punctuation, and white spaces)

  1. Using for loop:
for c in s:
    if c.isalpha():
        counter += 1
print(counter)
  1. Create a list of alphabets and count the length of the list: (It will create an unwanted list)
import re
s = "Nice. To. Meet. You."
letters = re.findall("([a-z]|[A-Z])", s)
counter = len(letters)
print(counter)

Can anyone tell me is there a "pythonic" way to achieve the same result? like single line code or a function called that will return an int which is the answer? Thank you very much.

3 Answers 3

2

Your first approach is perfectly pythonic, and probably the way to go. You could slightly simplify, using filter or a list comprehension as:

s = "Nice. To. Meet. You."
len(list(filter(str.isalpha, s)))
# 13

Or:

len([i for i in s if i.isalpha()])
# 13

Your second approach isn't really advisable, since you don't really need to use a regex for this. Note that you could simplify that pattern to ([a-zA-Z]), by the way.

Sign up to request clarification or add additional context in comments.

3 Comments

So as far as i understand, there are no method or function that we could call? like: xxxx(s) which return an int?
What do you mean? There is i.isalpha() but you have to apply it on every character @heihei
Sorry, I miss that line, i think len([i for i in s if i.isalpha()]) is already the best way. Thanks so much.
2

You can use regex to remove anything that is not a letter and then count the length of the string:

import re
s = "Nice. To. Meet. You."
counter = len(re.sub(r'[^a-zA-Z]','',s))

2 Comments

@JvdV, thanks for that! I updated my answer to only use alphabets
Thank you, another neat way!!
0

Using regex (re), you can find all letters and count their occurrence:

len(re.findall(r"[a-zA-Z]", string))

Comments

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.