Reputation: 1316
I have a string which has some chars and I need to generate a random uppercase char which is not found in my string.
Example: str = "SABXT" The random char can be any char which is not in str
I tried:
string.letters = "SABXT"
random.choice(string.letters)
but this do the opposite, it generates the char from my str
Upvotes: 0
Views: 275
Reputation: 113988
import string,random
prohibitted = "SABXT"
print random.choice(list(set(string.ascii_uppercase)-set(prohibitted)))
Is one way.
Another might be:
import string,random
prohibitted = "SABXT"
my_choice = random.randint(0,26)
while char(ord('A')+my_choice) in prohibitted:
my_choice = random.randint(0,26)
print char(ord('A')+my_choice)
Yet another way might be:
import string,random
my_choice = random.choice(string.ascii_uppercase)
while my_choice in prohibitted:
my_choice = random.choice(string.ascii_uppercase)
Upvotes: 1
Reputation: 402553
Get a list of characters that are not in your string, and then use random.choice
to return one of them.
import string
import random
p = list(set(string.ascii_uppercase) - set('SAXBT'))
c = random.choice(p)
Granted, the subsequent random.choice
may seem redundant since the set
shuffles the order, but you can't really depend on the set order for randomness.
Upvotes: 3