0

I am trying to exclude a certain value (specifically a space " ") from an iterative list comprehension and i'm not sure how to do that within the list comprehension.

I am building a simple password generator and I know how to do it later down by just doing an if else statement but i'm not quite sure how I would do it in the passcharacters.append(c) part. I want it to get all the ASCI characters apart from a space.

import random as rd

passlength = int(input('How long should the password be?:\n'))

passcharacters = []

for c in (chr(i) for i in range(32,127)):
    passcharacters.append(c)
print(passcharacters)

secure_random = rd.SystemRandom()

password = ""
for x in range(passlength):
    character = secure_random.choice(passcharacters)
    password = password + character

print("\nYour password is: \n"+password)
2
  • uhm.. i see a generator expression, that is iterated through and appended to a list. That should literally just be a list comprehension to begin with. Also, you can put if statements inside list comprehensions/generator expressions. Commented Feb 17, 2019 at 19:57
  • to excliude space just use range(33,127) :) Commented Feb 17, 2019 at 20:06

1 Answer 1

3

You should do a direct list comprehension instead of appending. List comprehensions and generator expressions both support conditionals:

passcharacters = [chr(i) for i in range(32,127) if chr(i) != ' ']

Another more readable way is this:

import string

passcharacters = list(string.printable.strip())

It's the same characters that you want, just in a different order. You can confirm this with

set(string.printable.strip()) == {chr(i) for i in range(32,127) if chr(i) != ' '}

which is True.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! Super helpful :D ... I forgot about that!
Anecdotally, do you happen to know what the difference between random.randomchoice and random.SystemRandom actually is?
@coconido Please avoid asking a different question; post another one of needed. Anyway, choice is in Python and SystemRandom is the system RNG. Also consider the secrets module if you want cryptographically strong RNG.
use set comprehension instead of list comprehension fed to a set
@Jean-FrançoisFabre Edited, though you won't use that code in this scenario. It's just for double checking that the two are the same.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.