Editor

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

string_compression.py
text = "aaabbccccd" # or: text = input("Enter a string: ")
compressed = ""
count = 1
for i in range(1, len(text) + 1):
if i < len(text) and text[i] == text[i - 1]:
count += 1 # same character as before: the run continues
else:
compressed += text[i - 1] + str(count) # the run has ended
count = 1
print("Original: ", text, "-", len(text), "characters")
print("Compressed:", compressed, "-", len(compressed), "characters")
if len(compressed) >= len(text):
print("Compression does not help here, so keep the original")
Output
Original:   aaabbccccd - 10 characters
Compressed: a3b2c4d1 - 8 characters

How it works

  1. The loop compares each character with the one before it, and count grows while they match.
  2. When the character changes, the finished run is written as the character followed by its count, and count starts again at 1.
  3. 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.
  4. 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()

Using itertools.groupby()
from itertools import groupby
text = "aaabbccccd"
compressed = ""
for ch, group in groupby(text):
compressed += ch + str(len(list(group)))
print(text, "->", compressed)
Output
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

Decompressing it again
compressed = "a3b2c12d1"
text = ""
i = 0
while i < len(compressed):
ch = compressed[i]
i += 1
digits = ""
while i < len(compressed) and compressed[i].isdigit():
digits += compressed[i] # a count can have several digits
i += 1
text += ch * int(digits)
print("Compressed:", compressed)
print("Original: ", text)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises