String compression function in python code 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 string:")
temp={}
result=" "
for x in s:
    if x in temp:
        temp[x]=temp[x]+1
    else:
        temp[x]=1
for key,value in temp.items():
    result+=str(key)+str(value)
        print(result)
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:

&gt;&gt;&gt; from your_file_name import compress
&gt;&gt;&gt; compress('aaabbccccddefg')
 a3b2c4d2e1f1g1
&gt;&gt;&gt; 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: ")))