2017-10-04 13 views
0

文字列があり、文字列に文字列がありません。文字列に文字列がありません。他の文字列にないランダムな文字を生成する

例: STR =「SABXT」 ランダムチャーは、私が試したSTR

ではない任意の文字とすることができる:

string.letters = "SABXT" 
random.choice(string.letters) 

をこれが逆の操作を行い、それからのチャーを生成します私のstr

+1

は、なぜあなたはSTRING' '、モジュールオブジェクトに割り当てていますか? 'string.letters =" SABXT "' ??? –

答えて

3

文字列に含まれていない文字のリストを取得し、random.choiceを使用してそれらのいずれかを返します。確かに

import string 
import random 

p = list(set(string.ascii_uppercase) - set('SAXBT')) 
c = random.choice(p) 

、その後のrandom.choicesetシャッフル順序ので、冗長に見えるかもしれませんが、あなたは本当にランダムのため、設定された順序に依存することはできません。

+0

ダング、私は学年を通じて遅くなってきた:P +1 –

+1

ナー、[この男のコメント]に応答しなければならなかった(https://stackoverflow.com/questions/46575590/how-do-i-print- Pythonの複数の入力のための機能の価値?noredirect = 1#comment80104700_46575590)(むしろ、彼が言ったことを見てください)。 –

1
import string,random 
prohibitted = "SABXT" 

print random.choice(list(set(string.ascii_uppercase)-set(prohibitted))) 

片道です。

別かもしれません:

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) 

さらにもう1つの方法は、次のようになります。

import string,random 
my_choice = random.choice(string.ascii_uppercase) 
while my_choice in prohibitted: 
    my_choice = random.choice(string.ascii_uppercase) 
+0

セット上の 'random.choice'呼び出しは次のように生成されます:' TypeError: 'set'オブジェクトはインデックス処理をサポートしていません '(python3.4) –

関連する問題