How do you find the occurrence of a character in a string using python?

How do I count the number of occurrences of a character in a string?

e.g. 'a' appears in 'Mary had a little lamb' 4 times.

How do you find the occurrence of a character in a string using python?

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

asked Jul 20, 2009 at 20:00

2

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4

How do you find the occurrence of a character in a string using python?

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

answered Jul 20, 2009 at 20:04

Ogre CodesOgre Codes

17.7k1 gold badge16 silver badges24 bronze badges

2

You can use .count() :

>>> 'Mary had a little lamb'.count('a')
4

How do you find the occurrence of a character in a string using python?

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

answered Jul 20, 2009 at 20:04

eduffyeduffy

38.2k12 gold badges93 silver badges91 bronze badges

To get the counts of all letters, use collections.Counter:

>>> from collections import Counter
>>> counter = Counter("Mary had a little lamb")
>>> counter['a']
4

How do you find the occurrence of a character in a string using python?

Mateen Ulhaq

22.2k16 gold badges86 silver badges127 bronze badges

answered Aug 1, 2012 at 22:12

Brenden BrownBrenden Brown

3,0551 gold badge13 silver badges15 bronze badges

4

Regular expressions maybe?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))

answered Jul 20, 2009 at 20:03

Sinan TaifourSinan Taifour

10.1k3 gold badges31 silver badges30 bronze badges

6

Python-3.x:

"aabc".count("a")

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

How do you find the occurrence of a character in a string using python?

tremendows

4,1943 gold badges31 silver badges51 bronze badges

answered Jul 20, 2009 at 20:05

Aaron FiAaron Fi

9,95613 gold badges64 silver badges91 bronze badges

1

myString.count('a');

more info here

answered Jul 20, 2009 at 20:04

Finer ReclinerFiner Recliner

1,5591 gold badge13 silver badges21 bronze badges

str.count(a) is the best solution to count a single character in a string. But if you need to count more characters you would have to read the whole string as many times as characters you want to count.

A better approach for this job would be:

from collections import defaultdict

text = 'Mary had a little lamb'
chars = defaultdict(int)

for char in text:
    chars[char] += 1

So you'll have a dict that returns the number of occurrences of every letter in the string and 0 if it isn't present.

>>>chars['a']
4
>>>chars['x']
0

For a case insensitive counter you could override the mutator and accessor methods by subclassing defaultdict (base class' ones are read-only):

class CICounter(defaultdict):
    def __getitem__(self, k):
        return super().__getitem__(k.lower())

    def __setitem__(self, k, v):
        super().__setitem__(k.lower(), v)


chars = CICounter(int)

for char in text:
    chars[char] += 1

>>>chars['a']
4
>>>chars['M']
2
>>>chars['x']
0

answered Oct 2, 2016 at 2:33

How do you find the occurrence of a character in a string using python?

Nuno AndréNuno André

3,8401 gold badge29 silver badges40 bronze badges

3

This easy and straight forward function might help:

def check_freq(x):
    freq = {}
    for c in set(x):
       freq[c] = x.count(c)
    return freq

check_freq("abbabcbdbabdbdbabababcbcbab")
{'a': 7, 'b': 14, 'c': 3, 'd': 3}

If a comprehension is desired:

def check_freq(x):
    return {c: x.count(c) for c in set(x)}

rayryeng

101k21 gold badges181 silver badges185 bronze badges

answered Mar 20, 2018 at 13:19

How do you find the occurrence of a character in a string using python?

0

Regular expressions are very useful if you want case-insensitivity (and of course all the power of regex).

my_string = "Mary had a little lamb"
# simplest solution, using count, is case-sensitive
my_string.count("m")   # yields 1
import re
# case-sensitive with regex
len(re.findall("m", my_string))
# three ways to get case insensitivity - all yield 2
len(re.findall("(?i)m", my_string))
len(re.findall("m|M", my_string))
len(re.findall(re.compile("m",re.IGNORECASE), my_string))

Be aware that the regex version takes on the order of ten times as long to run, which will likely be an issue only if my_string is tremendously long, or the code is inside a deep loop.

answered Dec 5, 2014 at 17:04

How do you find the occurrence of a character in a string using python?

jafeldsjafelds

8648 silver badges12 bronze badges

1

I don't know about 'simplest' but simple comprehension could do:

>>> my_string = "Mary had a little lamb"
>>> sum(char == 'a' for char in my_string)
4

Taking advantage of built-in sum, generator comprehension and fact that bool is subclass of integer: how may times character is equal to 'a'.

answered Sep 20, 2020 at 8:55

Aivar PaalbergAivar Paalberg

4,1584 gold badges16 silver badges16 bronze badges

a = 'have a nice day'
symbol = 'abcdefghijklmnopqrstuvwxyz'
for key in symbol:
    print(key, a.count(key))

How do you find the occurrence of a character in a string using python?

answered Oct 24, 2015 at 22:36

rookierookie

611 silver badge1 bronze badge

0

I am a fan of the pandas library, in particular the value_counts() method. You could use it to count the occurrence of each character in your string:

>>> import pandas as pd
>>> phrase = "I love the pandas library and its `value_counts()` method"
>>> pd.Series(list(phrase)).value_counts()
     8
a    5
e    4
t    4
o    3
n    3
s    3
d    3
l    3
u    2
i    2
r    2
v    2
`    2
h    2
p    1
b    1
I    1
m    1
(    1
y    1
_    1
)    1
c    1
dtype: int64

answered Jan 19, 2020 at 9:23

How do you find the occurrence of a character in a string using python?

1

count is definitely the most concise and efficient way of counting the occurrence of a character in a string but I tried to come up with a solution using lambda, something like this :

sentence = 'Mary had a little lamb'
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

This will result in :

4

Also, there is one more advantage to this is if the sentence is a list of sub-strings containing same characters as above, then also this gives the correct result because of the use of in. Have a look :

sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

This also results in :

4

But Of-course this will work only when checking occurrence of single character such as 'a' in this particular case.

answered Mar 28, 2017 at 17:13

How do you find the occurrence of a character in a string using python?

An alternative way to get all the character counts without using Counter(), count and regex

counts_dict = {}
for c in list(sentence):
  if c not in counts_dict:
    counts_dict[c] = 0
  counts_dict[c] += 1

for key, value in counts_dict.items():
    print(key, value)

answered Mar 7, 2019 at 9:04

a = "I walked today,"
c=['d','e','f']
count=0
for i in a:
    if str(i) in c:
        count+=1

print(count)

answered Sep 29, 2020 at 3:27

KquekKquek

574 bronze badges

2

I know the ask is to count a particular letter. I am writing here generic code without using any method.

sentence1 =" Mary had a little lamb"
count = {}
for i in sentence1:
    if i in count:
        count[i.lower()] = count[i.lower()] + 1
    else:
        count[i.lower()] = 1
print(count)

output

{' ': 5, 'm': 2, 'a': 4, 'r': 1, 'y': 1, 'h': 1, 'd': 1, 'l': 3, 'i': 1, 't': 2, 'e': 1, 'b': 1}

Now if you want any particular letter frequency, you can print like below.

print(count['m'])
2

answered Feb 3, 2021 at 11:42

Rishi BansalRishi Bansal

3,4372 gold badges24 silver badges44 bronze badges

To find the occurrence of characters in a sentence you may use the below code

Firstly, I have taken out the unique characters from the sentence and then I counted the occurrence of each character in the sentence these includes the occurrence of blank space too.

ab = set("Mary had a little lamb")

test_str = "Mary had a little lamb"

for i in ab:
  counter = test_str.count(i)
  if i == ' ':
    i = 'Space'
  print(counter, i)

Output of the above code is below.

1 : r ,
1 : h ,
1 : e ,
1 : M ,
4 : a ,
1 : b ,
1 : d ,
2 : t ,
3 : l ,
1 : i ,
4 : Space ,
1 : y ,
1 : m ,

answered Sep 23, 2021 at 5:06

How do you find the occurrence of a character in a string using python?

5

"Without using count to find you want character in string" method.

import re

def count(s, ch):

   pass

def main():

   s = raw_input ("Enter strings what you like, for example, 'welcome': ")  

   ch = raw_input ("Enter you want count characters, but best result to find one character: " )

   print ( len (re.findall ( ch, s ) ) )

main()

How do you find the occurrence of a character in a string using python?

answered Jan 11, 2015 at 17:24

B-YB-Y

1671 gold badge2 silver badges12 bronze badges

1

Python 3

Ther are two ways to achieve this:

1) With built-in function count()

sentence = 'Mary had a little lamb'
print(sentence.count('a'))`

2) Without using a function

sentence = 'Mary had a little lamb'    
count = 0

for i in sentence:
    if i == "a":
        count = count + 1

print(count)

answered Sep 7, 2019 at 20:16

Dipen GajjarDipen Gajjar

1,17813 silver badges22 bronze badges

the easiest way is to code in one line:

'Mary had a little lamb'.count("a")

but if you want can use this too:

sentence ='Mary had a little lamb'
   count=0;
    for letter in sentence :
        if letter=="a":
            count+=1
    print (count)

answered Dec 21, 2021 at 13:34

3

str = "count a character occurence"

List = list(str)
print (List)
Uniq = set(List)
print (Uniq)

for key in Uniq:
    print (key, str.count(key))

How do you find the occurrence of a character in a string using python?

answered Apr 1, 2016 at 1:29

How do you find the occurrence of a character in a string using python?

1

Taking up a comment of this user:

import numpy as np
sample = 'samplestring'
np.unique(list(sample), return_counts=True)

Out:

(array(['a', 'e', 'g', 'i', 'l', 'm', 'n', 'p', 'r', 's', 't'], dtype='

Check 's'. You can filter this tuple of two arrays as follows:

a[1][a[0]=='s']

Side-note: It works like Counter() of the collections package, just in numpy, which you often import anyway. You could as well count the unique words in a list of words instead.

answered Dec 29, 2021 at 19:29

How do you find the occurrence of a character in a string using python?

No more than this IMHO - you can add the upper or lower methods

def count_letter_in_str(string,letter):
    return string.count(letter)

answered Feb 23, 2016 at 19:16

How do you find the occurrence of a character in a string using python?

Tim SeedTim Seed

4,8862 gold badges27 silver badges26 bronze badges

You can use loop and dictionary.

def count_letter(text):
    result = {}
    for letter in text:
        if letter not in result:
            result[letter] = 0
        result[letter] += 1
    return result

How do you find the occurrence of a character in a string using python?

blackbishop

28.7k10 gold badges53 silver badges70 bronze badges

answered Dec 24, 2021 at 10:03

How do you find the occurrence of a character in a string using python?

spam = 'have a nice day'
var = 'd'


def count(spam, var):
    found = 0
    for key in spam:
        if key == var:
            found += 1
    return found
count(spam, var)
print 'count %s is: %s ' %(var, count(spam, var))

poolie

9,0421 gold badge46 silver badges73 bronze badges

answered Nov 15, 2015 at 19:05

How do you find the occurrences of a character in a string in Python?

One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.

How do you find the occurrence of a character in a string?

We can use the feature of lambdas and Stream for counting occurrences of a character in a string. First, we will use the Intstream class method - chars(), which will return a stream. Then, we will filter them using the Lambda expression with the search character and by using the filter() method.

How do you find the occurrence of a word in a string in Python?

The count() method returns the number of occurrences of a substring in the given string..
substring - string whose count is to be found..
start (Optional) - starting index within the string where search starts..
end (Optional) - ending index within the string where search ends..

How do you find the occurrence of a string?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.