我使用以下代码生成带符号,数字和数字的密码。
有时代码有效,有时无效,有什么问题?
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
答案 0 :(得分:3)
re.sub
将替换中\number
的序列解释为对模式(among other escape sequences)中的组的引用。您可以使用普通字符串替换:
template = template.replace('placeholder', latex_passwords)