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
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.