Exclude a particular character from being generated by random.choice()

Question:

I am trying to generate random characters using random.choice(string.ascii_lowercase). I do not want to include all the lowercase characters in the random.choice(). I want to exclude some

import random 
import string

random.choice(string.ascii_lowercase)

choice to select from
‘abcdefghijklmnopqrstuvwxyz’
exclude
‘abd’ from the choice generated by the random function

Asked By: Saranyan Senthivel

||

Answers:

Use this:

import random 
import string

unwanted_chars = 'abd'
random.choice([s for s in string.ascii_lowercase if s not in unwanted_chars])
Answered By: jfaccioni

You can remove all a,b,d characters by replacing them with an empty string:

import re

s = re.sub('[abd]', '', string.ascii_lowercase)
Answered By: Simon Crane
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.