随机密码生成器随机不起作用

时间:2018-03-13 22:53:26

标签: python regex random

我使用以下代码生成带符号,数字和数字的密码。

有时代码有效,有时无效,有什么问题?

import random
import string
import re

template="latex code... placeholder ...other latex code"
latex_passwords=''
for _ in range(30):
    password=''.join(random.choice(string.ascii_lowercase+string.digits+string.ascii_uppercase+string.punctuation) for _ in range(12))
    latex_passwords+=password+'\n'

template=re.sub(r'placeholder',latex_passwords,template)

其他详细信息:如果您运行代码10次,几乎有一半的时间会失败,并在re.sub()

的行中出现以下错误
  File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 887, in addgroup
raise s.error("invalid group reference %d" % index, pos)
sre_constants.error: invalid group reference 8 at position 169

1 个答案:

答案 0 :(得分:3)

re.sub将替换中\number的序列解释为对模式(among other escape sequences)中的组的引用。您可以使用普通字符串替换:

template = template.replace('placeholder', latex_passwords)