Home > Back-end >  Why does it only print one character (Python)
Why does it only print one character (Python)

Time:01-06

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.

CodePudding user response:

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)

CodePudding user response:

'''

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)

CodePudding user response:

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))

CodePudding user response:

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

CodePudding user response:

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)
  •  Tags:  
  • Related