0

If I have a string FOOBAR-efkem4x-dnj3mn-efjn2j-lf4m2l (in this format) I need to convert into a shorter string consisting of just numerical values [0-9] so I can put it as a unique number in the URL for my Django project.

So that string should be converted into something like 324982984829 (can be higher or lower length, doesn't matter as long it is all numeric). Decoding 324982984829 should get me back to FOOBAR-efkem4x-dnj3mn-efjn2j-lf4m2l.

The end numerical value should be unique for every unique string.

Is there any way of doing this?

4
  • Look at gist.github.com/sekondus/4322469 Commented May 25, 2014 at 22:03
  • 1
    If you happen to want obscurity, not security, see stackoverflow.com/questions/2490334/… Commented May 25, 2014 at 22:03
  • 2
    You can't encode the string to a shorter numerical string, but if you want a longer why not simply translate every character to its ord and add some 0's if needed for padding (if you are using only regular characters, 3 numerals per letter will be enough) Commented May 25, 2014 at 22:15
  • This is actually called encoding, not encryption (encryption requires a key to be used). tbrisker comment makes a good starting point. It may not be optimal though, you should create a special mapping from character to decimal value for that (that's tricky though, so if ordinals suffice, go for it). Commented May 25, 2014 at 23:21

1 Answer 1

1

Try a two-way dictonary which is a nice way to do that task. An working example looks like that:

class TwoWayDict(dict):
    def __setitem__(self, key, value):
        # Remove any previous connections with these values
        if key in self:
            del self[key]
        if value in self:
            del self[value]
        dict.__setitem__(self, key, value)
        dict.__setitem__(self, value, key)

    def __delitem__(self, key):
        dict.__delitem__(self, self[key])
        dict.__delitem__(self, key)

    def __len__(self):
        """Returns the number of connections"""
        # The int() call is for Python 3
        return int(dict.__len__(self) / 2)

d = TwoWayDict()
for i in range(10):
    d["FOOBAR-efkem4x-dnj3mn-efjn2j-lf4m2l"+str(i)] = str(i)



for i in range(10):
    print d['FOOBAR-efkem4x-dnj3mn-efjn2j-lf4m2l'+str(i)], "<->", d[str(i)]

Of course you can use any other numerical hash aswell.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.