Why does it only print one character?
import random
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890?!*-_.,'
b = ''
for i in range(10):
a = (random.choice(letters))
b = "".join(a)
print(b)
This is an example of what i get:
R
Im not trying to make a very good and safe password gen for commercial use, it's more about the concept and the learning.
you replace one letter in your loop, if you want to add +:
import random
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890?!*-_.,'
b = ''
for i in range(10):
a = (random.choice(letters))
b += a # here
print(b)
output:
Gg_LZ!?y-a
but also you can simplify abit:
import random
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890?!*-_.,'
a = ''.join(random.choice(letters) for i in range(10))
print(a)
also you might wanna use string
module:
import random
import string
a = ''.join(random.choice(string.ascii_letters + string.punctuation) for i in range(10))
print(a)
or you can use random.sample
:
import random
import string
b = "".join(random.sample(string.ascii_letters + string.punctuation,10))
print(b)
'''
import random
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890?!*-_.,'
b = []
for i in range(10):
a = (random.choice(letters))
b.append(a)
print(b)
['b', '5', 'K', 'J', '*', 'c', 'T', 'j', 'v', '5']
pw = ' '.join(b)
Here is another solution that will help you with learning, using list comprehension:
import random
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890?!*-_.,'
b="".join([random.choice(letters) for i in range(10)])
Or using string and numpy
import numpy as np
import string
letters=string.digits+string.ascii_letters+'?!*-_.,'
b="".join(np.random.choice(list(letters),size=10,replace=True))
If you want to use the join and not the +, you have to tell join it must join a and b:
import random
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890?!*-_.,'
b = ''
for i in range(10):
a = (random.choice(letters))
b = "".join([b,a])
print(b)
Sample outout:
p5qvFvairr
You've already gotten once solution. Here are to other changes to consider.
Option 1:
import random
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890?!*-_.,'
a = ''
for i in range(10):
a +=random.choice(letters)
print(a)
Option 2: Use sample
instead of repeatedly using choice
.
import random
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890?!*-_.,'
b = "".join(random.sample(letters,10))
print(b)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.