从字符串中取出某些部分,然后使用它来创建一个字符串变量

时间:2017-06-07 00:55:36

标签: python python-3.x

我试图创建一个来自列表的字符串变量 列表只是字母表(不要问为什么,它只是为了程序)

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"。

我将非常感谢您的回答,我试图从Fallout重新创建黑客迷你游戏,如果有人知道那是什么,谢谢!

3 个答案:

答案 0 :(得分:1)

我不确定我明白你要做什么,但...... 要创建一个等于“STOP”的字符串变量:

x = "STOP"

代码行

correctPassword = random.sample(passwords,4)

不会创建字符串变量,而是创建4个项目的字符串列表,每个项目都是1个字符的字符串。使用上面定义的x,表达式x == correctPassword将始终为false。

将这些合并为一个字符串:

correctPasswordAsString = ''.join(correctPassword)

如果correctPasswordAsString为“STOP”,则比较x == correctPasswordAsString为true,否则为false。

答案 1 :(得分: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()方法是一种字符串方法。它将对象列表合并为一个字符串。

答案 2 :(得分:0)

您可以按以下方式创建变量:

MATCH (currentBook:BOOK {ISBN: {ISBN}})-[sim:similar*1..3]-(newBook:BOOK {author: {currentAuthor}}) SET newBook.simsUsed = AMOUNT_EXPANDED(sim) RETURN newBook

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

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