Saranyan Senthivel
Saranyan Senthivel

Reputation: 73

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

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

Upvotes: 2

Views: 1632

Answers (2)

Simon Crane
Simon Crane

Reputation: 2182

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

import re

s = re.sub('[abd]', '', string.ascii_lowercase)

Upvotes: 1

jfaccioni
jfaccioni

Reputation: 7519

Use this:

import random 
import string

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

Upvotes: 3

Related Questions