How does the random.seed function in python work for words? What number is it converted to?

Question:

I realized that if I choose

random.seed("hello world!")

it actually works, i.e. it does not give me any error and it works like a normal seed; So for example choosing

random.seed("hello world!")
random.choices([1,2,3,4,5,6,7], k = 10)

keeps giving me the same output; But it would be actually interesting, to what number a string is converted to??

Asked By: Johannes

||

Answers:

The code in random.py looks like this:


# more code here

# Note there is a entirely different algorithm for "version 1"

elif version == 2 and isinstance(a, (str, bytes, bytearray)):
    if isinstance(a, str):
        a = a.encode()
    seed = int.from_bytes(a + _sha512(a).digest())

# some more irrelevant conditions

super().seed(seed)

So basically the number will be the "input string + sha512 of the input string" interpreted as one very big integer. Python integers have no max value so this always works.

Answered By: mousetail
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.