0

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

cs95
  • 379,657
  • 97
  • 704
  • 746
SMH
  • 1,276
  • 3
  • 20
  • 40

2 Answers2

3

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Dang it, I've gotten slower over the school year :P +1 – Christian Dean Oct 04 '17 at 23:25
  • 1
    Nah, had to respond to [this guys comment](https://stackoverflow.com/questions/46575590/how-do-i-print-values-of-a-function-for-multiple-inputs-in-python?noredirect=1#comment80104700_46575590) (rather, just see what he said). – Christian Dean Oct 04 '17 at 23:27
1
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)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • Any `random.choice` call on a set generates: `TypeError: 'set' object does not support indexing` (python3.4) – cs95 Oct 04 '17 at 23:26