Python Program to Compress a String
Intermediate · Strings
String compression here means replacing each run of the same character with the character and the length of the run, so "aaabbcccc" becomes "a3b2c4". This idea is called run-length encoding, and it saves space only when a string has long runs of repeated characters.
Program
Original: aaabbccccd - 10 characters Compressed: a3b2c4d1 - 8 characters
How it works
- The loop compares each character with the one before it, and
countgrows while they match. - When the character changes, the finished run is written as the character followed by its count, and
countstarts again at 1. - The loop runs one step past the end, up to
len(text), so the last run is written too;i < len(text)stops it reading past the string. - A string without repeats, like "abc", would become "a1b1c1", which is longer, so the program checks whether compression actually helped.
Other ways to write it
Using itertools.groupby()
aaabbccccd -> a3b2c4d1
groupby() splits the string into runs of the same character, so the program only has to write each character with the length of its run.
Decompressing it again
Compressed: a3b2c12d1 Original: aaabbccccccccccccd
Counts can have more than one digit, like 12, so the inner loop collects every digit after a character. This only works when the original text has no digits of its own.
Try it yourself
Run the program on "abcd" and on "wwwwwwwwwwwwb" and compare how much each one shrinks or grows.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Count the Frequency of Each Character in a String
- Remove Duplicate Characters from a String
- Find Duplicate Characters in a String
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Words in a String
- Remove Punctuation from a String
All Python programs · CBSE class 12 practical file · Python exercises