有效地生成一个16个字符的字母数字字符串 [英] Efficiently generate a 16-character, alphanumeric string

查看:219
本文介绍了有效地生成一个16个字符的字母数字字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种非常快速的方法来为表中的主键生成字母数字唯一标识符。



会是这样的吗?

  def genKey():
hash = hashlib.md5(RANDOM_NUMBER).digest()。encode(base64)
alnum_hash = re.sub(r'[^ a-zA-Z0-9]',,hash)
返回alnum_hash [:16]

什么是生成随机数的好方法?
如果我将它基于microtime,我必须考虑从不同实例同时调用几次genKey()的可能性。



或者是有没有更好的方法来做这一切?

解决方案

由于没有答案为您提供随机字符串组成的字符0- 9,AZ,AZ:这是一个工作解决方案,它会给你约。 4.5231285e + 74键:

  import random,string 
x =''.join(random.choice(string。 ascii_uppercase + string.ascii_lowercase + string.digits)for _ in range(16))
print(x)

在不知道ASCII码的情况下,它也是非常易读的。

python 3.6.2

  import random,string 
x =''.join(random.choices(string .ascii_letters + string.digits,k = 16))
print(x)


I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table.

Would something like this work?

def genKey():
    hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64")
    alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash)
    return alnum_hash[:16]

What would be a good way to generate random numbers? If I base it on microtime, I have to account for the possibility of several calls of genKey() at the same time from different instances.

Or is there a better way to do all this?

解决方案

As none of the answers provide you with a random string consisting of characters 0-9, a-z, A-Z: Here is a working solution which will give you approx. 4.5231285e+74 keys:

import random, string
x = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(16))
print(x)

It is also very readable without knowing ASCII codes by heart.

There is an even shorter version since python 3.6.2:

import random, string
x = ''.join(random.choices(string.ascii_letters + string.digits, k=16))
print(x)

这篇关于有效地生成一个16个字符的字母数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆