Vincent Vincent - 1 month ago 12
Python Question

How to hash strings into a float in [0:1]?

I have a dataset with multiple strings. I want to associate each of these strings to a float, "randomly" distributed in the

[0:1]
range. Examples:

>>> myfunction(string_1)
0.26756754
>>> myfunction(string_2)
0.86764534


random
does not fulfill my need because it does not take any string as input/deterministic parameter. I am looking for something more like a hash function.

Answer

You could try something like this:

import random
random.seed(hash(your_string))
random.random()