How to count the number of alphabets in a given string in Python using regular expression

Hello guys this is Satyam,again back with another awesome blog and in this blog I am going to explain you that how you can count the number of alphabets in a given string in python using regular obviously the pre requisite for this blog is that you should have a basic knowledge of python programming language and regular expression.If you don't meet this pre requisite then I will suggest you to check out my tutorial on Regular Expression:

Let's see the code:

import re 
def count_alphabets(str):
  pattern = re.compile(r'[A-Za-z]')
  matches = re.findall(pattern,str)

So,guys in the very first line of the code we have imported the required module 're' which is used to deal with regular expression stuffs in python.Now I have taken a functional approach and I have created a simple method in which the 'pattern' variable is used to find a pattern that is in this case we are looking for alphabets of both cases(upper and lower as you can see the compile method with A-Za-z arguments,and in the next line we have stored the matches in the matches variable using the findall() method which stores all the values in  a list and hence you can see that in the second last line of the code I have printed the length using the len() method because matches is a list of string and at last I have called the count_alphabets() method with a string value.

Thanks for Reading


Post a Comment

Copyright © DevTipsNTricks. Designed by OddThemes