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
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])
You can remove all a,b,d characters by replacing them with an empty string:
import re
s = re.sub('[abd]', '', string.ascii_lowercase)
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
Use this:
import random
import string
unwanted_chars = 'abd'
random.choice([s for s in string.ascii_lowercase if s not in unwanted_chars])
You can remove all a,b,d characters by replacing them with an empty string:
import re
s = re.sub('[abd]', '', string.ascii_lowercase)