如何在输出之间自动添加破折号?

时间:2017-12-03 04:57:35

标签: python cryptography passwords

import random
import string

oneFile = open('password.txt', 'w')
userInput = 0
key_count = 0
key = []
chars = string.ascii_uppercase + string.digits + string.ascii_lowercase

for userInput in range(int(input('How many keys needed?'))):
    while key_count <= userInput:
        number = random.randint(1, 999)
        if number not in key:
            key_count += 1
            key.append(number)
            text = str(number) + ": " + str(''.join(random.sample(chars*6, 16)))
            oneFile.write(text + "\n")

oneFile.close()

print("Data written, please Rename or it will be over written.")
raw_input("press enter to exit")

我如何得到它所以输出看起来像这样:
955:PFtKg-r1fd1-g9FX23在选定数量的字符后夹在中间?

text = str(number) + ": " + str(''.join(random.sample(chars*6, 16)))
#puts everything together but i would have to repeat
#  + str(''.join(random.sample(chars*6, 16)))  on the line in code

3 个答案:

答案 0 :(得分:1)

用随机字符的三个单词中断密码,然后按' - '(连字符)加入。所以,您的密码将是:

completePassword = pass[0] + '-' + pass[1] + '-' + pass[2]

答案 1 :(得分:1)

基于this您可以写(dashPer表示选定数量的字符):

'-'.join(text[i:i+dashPer] for i in range(0, len(text), dashPer))

就像刚刚取代:

text = str(number) + ": " + str(''.join(random.sample(chars*6, 16)))

使用:

dashPer = 5
text = str(''.join(random.sample(chars*6, 16)))
text = '' + '-'.join(text[i:i+dashPer] for i in range(0, len(text), dashPer))
text = str(number) + ": " + text

答案 2 :(得分:0)

一个解决方案可以是在随机字符生成块中使用另一个if条件来检查计数器生成的字符数,如果是某个数字则添加破折号并重置计数器。可能有更好的答案,但这肯定会有效。

或一次生成四个随机字符并用破折号附加它们直到enxt运行程序。