【问题标题】:How do I save a variable in a string, and then save that in a list?如何将变量保存在字符串中,然后将其保存在列表中?
【发布时间】:2022-12-10 12:29:01
【问题描述】:

我正在尝试选择你自己的冒险,我想将每个场景保存为列表的一部分,例如“场景列表”将包含

scenariolist = ['you come to a path split', 'you come to another path split', 'you come to a third path split', etc.]

然后该函数将根据保存游戏状态的另一个列表的长度和最后一个数字来提取正确的场景。

例子

print scenariolist[len(gamestate)]

其中,如果玩家在第三条路径分裂上,将打印

"you come to a third path split"

我想要做的是能够将一个变量与该行的其余部分一起保存在字符串中,就像

"Playername comes to a path split".

如果 playername 设置为“bob”,当打印列表元素时,我想让它打印

"bob comes to a path split"

而不是

"playername comes to a path split" 如何保存它,以便变量在从列表中拉出后仍然可以调用,而不是仅仅打印变量名?

【问题讨论】:

标签: python python-3.x list variables pycharm


【解决方案1】:

提示输入玩家姓名并将输入保存在名为 player_name 的变量中。然后将 player_name 与路径字符串连接起来。

player_name = input()

paths =  ['you come to a path split', 'you come to another path split', 'you come to a third path split']

for path in paths:
    print(player_name + " " + path)

输出:

bob you come to a path split
bob you come to another path split
bob you come to a third path split

【讨论】:

    【解决方案2】:

    您好,您可以使用 python 字符串格式,如下所示:

    my_variable = "bob"
    my_string = "Hi I am {name} nice to meet you!"
    
    print(my_string.format(name=my_variable))
    # "Hi I am bob nice to meet you!"
    

    这里有一些文档:https://docs.python.org/3/tutorial/inputoutput.html#the-string-format-method

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-24
      • 2016-12-23
      • 1970-01-01
      • 2015-12-17
      • 2021-12-11
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      相关资源
      最近更新 更多