2017-06-07 28 views
0

我試圖創建一個變量,這是從列表 列表中的字符串就是字母表(不要問爲什麼,它只是爲該程序)採取某些部分從字符串,然後用它來創建一個字符串變量

passwords = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] 

基本上,我曾經有帶4個隨機字母從它的變量,以創建一個看起來像這樣的字符串:

correctPassword = random.sample(passwords,4) 

我需要的是從4個特定字符列表創建相同類型的字符串變量,單詞「STOP」。

對此的答案將不勝感激,我試圖重新創建來自輻射的黑客小遊戲,如果你們中的任何人知道那是什麼,謝謝!

+2

請顯示您迄今嘗試解決此問題的方法。用你的代碼解釋你面臨的問題。 – idjaw

+2

你可以嘗試和更清楚一點嗎? – Rosh

+0

由於信件是爲了,不能你只需要使用的S,T,O,P的指數的指數? –

回答

0

你可以使用這個從列表中創建一個字符串變量:

import random 
passwords = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] 
correctPassword = random.sample(passwords,4) 
result = "" 
result = result.join(correctPassword) 
print(result) 

,並得到類似:STOP

Python的join()方法是一個字符串的方法。它將對象列表合併爲一個字符串。

0

您只需創建變量如下所示:

correctPassword = ["S", "T", "O", "P"]

或者,你可以使用字母索引:

correctPassword = [passwords[18], passwords[19], passwords[14], passwords[15]]

1

我不知道我的理解你要做什麼,但... 要創建一個字符串變量等於「停止」:

x = "STOP" 

的代碼

correctPassword = random.sample(passwords,4) 

線不創建字符串變量,但4項長字符串的列表,每一個項目是一個1個字符的字符串。使用上面定義的x,表達式x == correctPassword將始終爲假。

鞏固這些成一個字符串:

correctPasswordAsString = ''.join(correctPassword) 

比較x == correctPasswordAsString將如果correctPasswordAsString是 「STOP」,否則爲假爲真。

相關問題