String Compression

Implement a simple run-length encoding (RLE) compression for strings.

IntermediateTopic: String Programs
Back

Python String Compression Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Program for simple string compression (run-length encoding)

s = input("Enter a string: ")

if not s:
    print("Compressed string: ")
else:
    result = []
    count = 1
    for i in range(1, len(s)):
        if s[i] == s[i - 1]:
            count += 1
        else:
            result.append(f"{s[i-1]}{count}")
            count = 1
    result.append(f"{s[-1]}{count}")

    compressed = "".join(result)
    print("Compressed string:", compressed)
Output
Enter a string: aaabbc
Compressed string: a3b2c1

Understanding String Compression

We count consecutive repeating characters and append character+count pairs to build a compressed representation.

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents