Python Forum
Counting the number of occurrences of characters in a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Counting the number of occurrences of characters in a string
#1
Hey everyone,

I was presented with a challenge where I need to code a function that takes a string and then counts the number of times each character occurs in the string. Here's an example:

Input: "occurrences"

output: o1c3u1r2e2n1s1

I know the rules about no effort posts but I don't really know where to start other than taking the string, passing it into the function, and then putting the string into a list. After that do I create another list of unique characters to count them? Use a dictionary to store the results? How would I go about printing out the result like such?
Reply
#2
Strings are already iterators in python. Take a look at the standard library and the Counter type. It lets you easily count from an iterator.

I think if you play with the examples, you'll have some ideas.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with extracting characters from string valentino1337 2 519 Feb-19-2024, 01:17 PM
Last Post: Pedroski55
  String to Number in Python Godjuned 3 1,365 Nov-17-2022, 07:22 AM
Last Post: Godjuned
  number to string Ali_ 1 1,288 Mar-31-2022, 11:22 AM
Last Post: ndc85430
  Replacing a few characters of a specified character but not all of them from a string fatherted99 7 3,255 Aug-13-2020, 09:08 AM
Last Post: fatherted99
  Convert string to a specific number of bytes artblinked 1 2,434 Mar-28-2019, 08:43 PM
Last Post: Larz60+
  counting chars in string w/o len johneven 2 4,125 Mar-20-2019, 07:11 PM
Last Post: ichabod801
  slicing and counting words in a string Rudy 11 6,455 Mar-17-2019, 10:46 PM
Last Post: micseydel
  testing indivudual string for alternating characters Titus444 3 2,681 Nov-01-2018, 10:28 PM
Last Post: j.crater
  Counting only letters in a string PraiseYAH 2 4,560 Jul-20-2018, 11:22 AM
Last Post: ichabod801
  How to exclude characters when counting digits juliabrushett 19 9,370 Jul-03-2018, 08:59 PM
Last Post: volcano63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020