[Tutor] Counting number of occurrence of each character in a string

Ian Clark ianhclark510 at gmail.com
Thu Sep 3 19:55:32 EDT 2020


I would certainly recommend the Counter object from Collections
https://docs.python.org/3.8/library/collections.html#counter-objects

from collections import Counter
x = "ABRACADABRA"
x_counter= Counter(x)
for key, value in x_counter.items():
    print(key,value)



On Thu, Sep 3, 2020 at 3:42 PM boB Stepp <robertvstepp at gmail.com> wrote:

> On Wed, Sep 02, 2020 at 03:49:40PM +0530, Manprit Singh wrote:
> >Dear sir ,
> >consider a problem of Counting number of occurrence of each  character in
> a
> >string
> >x = "ABRACADABRA"
> >in this string x :
> >Number of occurrence of   character A = 5
> >Number of occurrence of   character B = 2
> >Number of occurrence of   character R = 2
> >Number of occurrence of   character C = 1
> >Number of occurrence of   character D = 5
>
> I don't know if this is an abstract problem to explore Python or not, but
> if instead you are doing something like solving a cryptogram, you probably
> do not want to make a distinction between uppercase and lowercase for your
> frequency data.
>
> --
> Wishing you only the best,
>
> boB Stepp
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list