I can't figure out why there are spaces in this returned list

49 views Asked by At

I've included the whole problem statement and the code used. As I tried two alternative formulations of the char_list structure both have been included and commented out; the problem persisted in both cases.

Why doesn't ' '.join() clean out the spaces?

'''Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time code in a main method.'''


import random

def password_generator():

  #char_str = '1234567890abcdefgh!@#$%(^)%($('
  #char_str = ['a', 'b', 'c', 'd', '1', '2', '3', '4']
  password = []
  length = int(input("How long should the password be?"))

  while len(password) < length:
    password.append(char_str[random.randint(0, len(char_str) - 1)])

  return(' '.join(password))

print(password_generator())

Example output: % ) 0 4 d c f b % 7

2

There are 2 answers

0
Matthew Story On

You are joining each character by a literal space, which is why there are spaces between each character. To solve this you could join on an empty string:

"".join(password)

Or alternatively you could just build a string instead of a list:

password = ""
while len(password) < length:
    password += char_str[random.randint(0, len(char_str) - 1]
0
sargeMonkey On

' '.join(password) does that. Do ''.join(password) instead.