kee
kee

Reputation: 11629

How to create a random string from a few string keys in Python 3

I would like to create some kind of UUID type of random string from a list of other input strings (timestamp, user ID and so on). I found examples of creating a purely random string but I would like to create something deterministic from a given set of inputs. Thanks!

Upvotes: 0

Views: 679

Answers (2)

leonh
leonh

Reputation: 846

An alternative to the uuid3 and uuid5 functions mentioned in previous answers may be to use a hash function.

Python provides several as part of the hashlib package. Your code might look something like this:

import hashlib

h = hashlib.sha1()
# Changing the order (timestamp and user id) will change the output!
h.update(str(my_datetime.timestamp() + str(my_user_id))
print(h.hexdigest())

Upvotes: 1

user4396006
user4396006

Reputation:

Use the UUID module in Python

import uuid

print uuid.uuid1()

This creates a random UUID. If you want a custom one, check this out from the documentation:

uuid.uuid1([node[, clock_seq]]) Generate a UUID from a host ID, sequence number, and the current time. If node is not given, getnode() is used to obtain the hardware address. If clock_seq is given, it is used as the sequence number; otherwise a random 14-bit sequence number is chosen.

uuid.uuid3(namespace, name) Generate a UUID based on the MD5 hash of a namespace identifier (which is a UUID) and a name (which is a string).

uuid.uuid4() Generate a random UUID.

uuid.uuid5(namespace, name) Generate a UUID based on the SHA-1 hash of a namespace identifier (which is a UUID) and a name (which is a string).

In this way, you can call any of those functions (providing the required arguments) to get a custom UUID fitting your needs. Look at that most of them already take into account the factors you described you wanted to take into account.

If you really want to get a totally custom UUID based in your name, your birth date or anything in the world, look up the UUID format and generate a random string based in the variables you've got.

Upvotes: 2

Related Questions