Here are two ways in Python to count occurrences in a string. These include using the itertools and for loop.

python count occurrences in string
Photo by Juan Pablo Serrano Arenas on Pexels.com

Table of contents

  1. Python count occurrences in a string
    1. Method 01: Use itertools and groupby
    2. Method 02: Use for loop
  2. Audio explanation
  3. Conclusion
  4. References

Python count occurrences in a string

The question is. I have the following string a=”AABBBCCCDDDD”, I need output in the following way: output=”A2B3C2D4″

Method 01: Use itertools and groupby

from itertools import groupby

a = "AABBBCCDDDD"

output = ""

for key, group in groupby(a):
    count = len(list(group))
    output += key + str(count)

print(output)

Output

A2B3C2D4


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Method 02: Use for loop

a = "AABBBCCDDDD"
output = ""
count = 1

for i in range(1, len(a)):
    if a[i] == a[i-1]:
        count += 1
    else:
        output += a[i-1] + str(count)
        count = 1

output += a[-1] + str(count)

print(output)

Output

A2B3C2D4


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Audio explanation

Conclusion

In conclusion, we’ve looked at two ways to count how many times characters appear in a string using Python. We showed how to use the ‘itertools’ module and the ‘groupby’ function, as well as how to do the same thing with a ‘for’ loop. Both ways gave us the result we wanted, demonstrating how flexible Python is for working with strings. By understanding these different methods, you can choose the one that fits your specific needs and coding style best. We hope this guide has helped improve your Python programming skills.

References