1

I'm trying to generate a unique password with a function. Everything works fine, except "".join. Help me see whats the problem in the code? Using Python 3.7.

My code:

import random
import string


def password():
    a = []
    letters = string.ascii_letters
    symbols = string.punctuation
    for element in range(6):
        a.append(random.randint(0, 10))
        a.append(random.choice(letters))
        a.append(random.choice(symbols))
    random.shuffle(a)
    print(''.join(str(a)))


password()
Phydeaux
  • 2,795
  • 3
  • 17
  • 35
Sosofofie
  • 65
  • 1
  • 1
  • 7

1 Answers1

1

When you call join over str(a), you are first converting the list to a string, and then joining over every character in the stringified list.

What you want to do instead is convert each element in a to a string. You should use a generator expression, like this:

''.join(str(x) for x in a)

Alternatively, you can use the built-in function map(function, iterable), which is useful in the general case when you want to return a new iterable containing the results of function applied to every element in iterable. So you would use:

''.join(map(str, a))

It's basically a matter of taste as to which you find more readable.

Phydeaux
  • 2,795
  • 3
  • 17
  • 35