How about zlib?

import zlib

a = "this string needs compressing"
a = zlib.compress(a.encode())
print(zlib.decompress(a).decode())  # outputs original contents of a

You can also use sys.getsizeof(obj) to see how much data an object takes up before and after compression.

Answer from hmir on Stack Overflow
🌐
Python Pool
pythonpool.com › home › blog › achieving string compression in python
Achieving String Compression in Python - Python Pool
June 14, 2021 - String compression in python basically means to shorten any string whose length is very long. Compressing the string will never change the original intent of the string.
Discussions

compression - Create a compress function in Python? - Stack Overflow
I need to create a function called compress that compresses a string by replacing any repeated letters with a letter and number. My function should return the shortened version of the string. I've ... More on stackoverflow.com
🌐 stackoverflow.com
String compression function in python code - Code Review Stack Exchange
I need to create a function called compress that compresses a string by replacing any repeated letters with a letter and number. Can someone suggest a better way to do this? s=input("Enter the str... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
August 1, 2019
String compression using dictionary [Python]
Sorry, but you have completely misunderstood how RLE (Run Length Encoding) works. In RLE you only count consecutive characters. So the sequence AABBAABB should produce A2B2A2B2. More on reddit.com
🌐 r/learnprogramming
5
1
December 2, 2017
compress a string in python 3? - Stack Overflow
In python 2.x strings are bytes string by default. In python 3.x they are unicode strings. Compressing needs a byte string. More on stackoverflow.com
🌐 stackoverflow.com
🌐
PySeek
pyseek.com › home › writing a python program for string compression
Writing a Python Program for String Compression - PySeek
July 9, 2024 - Now, let’s implement a simple string compression program in Python. We’ll define a function called `compress_string` that takes an input string and returns its compressed version if the compression leads to a shorter representation.
🌐
Medium
medium.com › @hamnaqaseem › leetcode-443-string-compression-python-solution-77b28c762e34
LeetCode # 443: String Compression — Python Solution | by Hamna Qaseem | Medium
July 19, 2023 - Example 1: Input: chars = ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3". Begin with an empty string s.
🌐
TutorialsPoint
tutorialspoint.com › article › program-to-perform-string-compression-in-python
Program to perform string compression in Python
from itertools import groupby def compress_string(s): result = "" for char, group in groupby(s): count = len(list(group)) if count == 1: result += char else: result += char + str(count) return result s = "abbbaaaaaaccdaaab" print(compress_string(s))
🌐
coderz.py
coderzpy.com › home › string compression in python
String Compression in Python - coderz.py
April 11, 2026 - Known as the RunLength Compression algorithm. """ # Begin Run as empty string r = "" l = len(s) # Check for length 0 if l == 0: return "" # Check for length 1 if l == 1: return s + "1" #Intialize Values last = s[0] cnt = 1 i = 1 while i < l: # Check to see if it is the same letter if s[i] == s[i - 1]: # Add a count if same as previous cnt += 1 else: # Otherwise store the previous data r = r + s[i - 1] + str(cnt) cnt = 1 # Add to index count to terminate while loop i += 1 # Put everything back into run r = r + s[i - 1] + str(cnt) return r
Find elsewhere
Top answer
1 of 3
11

Encapsulate your code into functions

Your code is neither reusable nor testable, wrap it into a function and call it from under an if __name__ == '__main__' guard. This will allow you to test it more easily. You will also be able to return values instead of printing them, this will make the code more reusable:

def compress(string):
    temp={}
    result=" "
    for x in string:
        if x in temp:
            temp[x] = temp[x]+1
        else:
            temp[x] = 1
    for key, value in temp.items():
        result += str(key) + str(value)

    return result


if __name__ == '__main__':
    s = input("Enter the string:")
    print(compress(s))

You can then jump into an interactive shell and type:

>>> from your_file_name import compress
>>> compress('aaabbccccddefg')
 a3b2c4d2e1f1g1
>>> compress('b'*42)
 b42

Use existing data structures

collections.Counter offers simplified ways of counting elements of an iterable:

from collections import Counter


def compress(string):
    temp = Counter()
    result = " "
    for x in string:
        temp[x] += 1

    for key, value in temp.items():
        result += str(key) + str(value)
    return result


if __name__ == '__main__':
    s = input("Enter the string:")
    print(compress(s))

You can even simplify further as Counter can take any iterable in its constructor. You can also use str.join to simplify even further:

from collections import Counter


def compress(string):
    counts = Counter(string)
    return ''.join(letter+str(count) for letter, count in counts.items())


if __name__ == '__main__':
    print(compress(input("Enter the string: ")))

Possible bug

To me, compressing a string mean having a mean to decompress it back. Using a dictionnary keyed by each letter as you do, you lost an important information: which letter is next to which one. Also 'aabaabaabaa' will be compressed to 'a8b3' which, to me, doesn't make sense and would be better as 'a2b1a2b1a2b1a2'. But I might be wrong. In this case, itertools.groupby is much more usefull as it will keep the ordering and avoid aggregating separate groups of letters:

import itertools


def compress(string):
    return ''.join(
            letter + str(len(list(group)))
            for letter, group in itertools.groupby(string))


if __name__ == '__main__':
    print(compress(input("Enter the string: ")))
2 of 3
2

In the itertools module there is the groupby function that groups together runs of the same values.

You can use it like this here:

from itertools import groupby

def compress(s):
    out = []
    for name, group in groupby(s):
        length_of_run = len(list(group))
        if length_of_run == 1:
            out.append(name)
        else:
            out.append(f"{name}{length_of_run}")
    return "".join(out)

This also uses the more modern f-strings instead of manually building the string with str calls and + and puts everything into a function that you can reuse.

It also has the advantage that it directly iterates over the input, instead of over its indices (have a look at Loop like a Native!). This makes it work also for a generator, which does not have a length:

from itertools import islice, cycle

compress(islice(cycle('a'), 10))
# 'a10'
🌐
LeetCode
leetcode.com › problems › string-compression
String Compression - LeetCode
String Compression - Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: * If the group's length is 1, append the character ...
🌐
Reddit
reddit.com › r/learnprogramming › string compression using dictionary [python]
r/learnprogramming on Reddit: String compression using dictionary [Python]
December 2, 2017 -

I'm doing some practice interview questions and doing the problem below.

Problem

Given a string in the form 'AAAABBBBCCCCCDDEEEE' compress it to become 'A4B4C5D2E4'. For this problem, you can falsely "compress" strings of single or double letters. For instance, it is okay for 'AAB' to return 'A2B1' even though this technically takes more space.

The function should also be case sensitive, so that a string 'AAAaaa' returns 'A3a3'.

For my solution I decided to use the following approach.

Go through the string, For each character keep track of how many times they occur in a hashtable/dictionary.

def string_compression(string):
    counter = {}
    for s in string:
        if s in counter:
            counter[s] += 1
        else:
            counter[s] = 1
            
    return "".join(['{0}{1}'.format(k, v) for k, v in counter.iteritems()])

The only problem I have with this solution is the order of Alphabets i.e AABBCC will return A2C2B2other than that, this seems to pass all the test cases.

I've seen the following used as a solution.

def compress(s):
    """
    This solution compresses without checking. Known as the RunLength Compression algorithm.
    """
    
    # Begin Run as empty string
    r = ""
    l = len(s)
    
    # Check for length 0
    if l == 0:
        return ""
    
    # Check for length 1
    if l == 1:
        return s + "1"
    
    #Intialize Values
    last = s[0]
    cnt = 1
    i = 1
    
    while i < l:
        
        # Check to see if it is the same letter
        if s[i] == s[i - 1]: 
            # Add a count if same as previous
            cnt += 1
        else:
            # Otherwise store the previous data
            r = r + s[i - 1] + str(cnt)
            cnt = 1
            
        # Add to index count to terminate while loop
        i += 1
    
    # Put everything back into run
    r = r + s[i - 1] + str(cnt)
    
    return r

My question is, is there any issues with my approach? especially when it comes to performance? IIRC, looking up and setting items in a python Dictionary is O(1)

🌐
Finxter
blog.finxter.com › 5-best-ways-to-perform-string-compression-in-python
5 Best Ways to Perform String Compression in Python – Be on the Right Side of Change
This snippet uses the itertools.groupby() function to create an iterator that returns consecutive keys and groups from the string. We then iterate through these groups, construct a compressed format of the key and the length of the group, and join them into a resulting string.
🌐
Sololearn
sololearn.com › en › Discuss › 2185664 › how-to-compress-string-in-python-i-am-not-getting-proper-output-can-you-please-help-me
How to compress string in python I am not getting proper output can you please help me | Sololearn: Learn to code for FREE!
If we are talking about RLE (run length encoded) we can use python itertools takewhile(). It does group consecutive characters, that can be encoded in an easy way. ... rodwynnejones, your code sample does collect for example all "a", so the output is not correct in terms of RLE: 7a6b4c ... May be you should have a look first of all to what the code is producing: Input string: abbc deffg hiiki result from program: 1a2b1a2b1c1 1d1e2f1a2b1c1 1d1e2f1g1 1h2i result expected: 1a2b1c 1d1e2f1g 1h2i1k1i if spaces should be also handled, encoding should be like this: 1a2b1c1 1d1e2f1g1 1h2i1k1i
🌐
AlgoCademy
algocademy.com › blog › string-compression-and-encoding-algorithms-a-comprehensive-guide
String Compression and Encoding Algorithms: A Comprehensive Guide – AlgoCademy Blog
Initialize a dictionary with single-character strings. Read input characters and build longer substrings. If a substring is not in the dictionary, add it and output the code for the previous substring. If a substring is in the dictionary, continue building a longer substring. Repeat until the entire input is processed. Here’s a basic implementation of LZW compression in Python:
🌐
GeeksforGeeks
geeksforgeeks.org › python › gzip-compresss-in-python
gzip.compress(s) in Python - GeeksforGeeks
March 23, 2020 - With the help of gzip.compress(s) method, we can get compress the bytes of string by using gzip.compress(s) method.
🌐
GitHub
github.com › CordySmith › PySmaz
GitHub - CordySmith/PySmaz: A Python port of SMAZ small text string compression library · GitHub
SMAZ throughput on small strings is approximately equal to bz2 and zlib, due to the high setup cost per call to the entropy coders. SMAZ by Salvatore Sanfilippo, Python port by Max Smith. ... from smaz import compress, decompress print compress("Hello, world!") print compress("https://gith...
Starred by 33 users
Forked by 6 users
Languages   Python 63.1% | HTML 23.0% | C 10.4% | Common Lisp 3.5%
🌐
YouTube
youtube.com › codesolve
python compress string - YouTube
Instantly Download or Run the code at https://codegive.com in this tutorial, we will explore various methods to compress strings in python. string compressi...
Published   March 29, 2024
Views   2
🌐
DEV Community
dev.to › codeperfectplus › compress-the-string-hackerrank-solution-python-7ne
Compress the String! - HackerRank Solution Python - DEV Community
September 12, 2023 - The next function, compress_the_string(), takes a string as input and returns a compressed version of the string. The function first uses the itertools.groupby() function to group the characters in the string together based on their equality.
🌐
GeneUs Programmer
geneusprogrammer.com › home › string compression in python, imperative & functional ways
String Compression in Python, Imperative & Functional Ways - GeneUs Programmer
June 25, 2020 - There I was solving in C#. However, I would never miss the opportunity to do that in Python! So here we go. The assignment was to write a function to count similar letters in the input string and give the output in compressed form {number}{letter}. Below are several examples in the format input ...