代码之家  ›  专栏  ›  技术社区  ›  CrispyCashew

Python从文件中读取字符串,保留要打印的变量

  •  0
  • CrispyCashew  · 技术社区  · 7 年前

    我正在制作一个Python脚本,它将从列表中随机选择一个响应。

    "This number is " + str(num) + ", this is good"
    "Oh no the number is " + str(num) +", this is good
    

    显然,这些是作为字符串从文件中读取的,因此如果我打印其中一个字符串,它们将显示为您在这里看到的内容,并且不会替换“num”的值。有没有办法从文件中读取这些字符串,同时保持替换变量(如原始格式)的能力,就像我的代码那样

    list.append("This number is " + str(num) + ", this is good")
    

    谢谢

    2 回复  |  直到 7 年前
        1
  •  1
  •   Kevin    7 年前

    你可以使用 format specification mini-language ,然后致电 .format 在显示字符串之前。

    串。txt:

    This number is {num} this is good
    Oh no the number is {num} this is good
    

    import random
    
    with open("strings.txt") as file:
        possible_strings = file.read().split("\n")
    
    number = 23
    
    s = random.choice(possible_strings)
    print(s.format(num=number))
    

    可能输出:

    This number is 23 this is good
    
        2
  •  1
  •   Scott Hunter    7 年前

    例如,如果需要输入 num ,您的文本可以使用 {{num}} 需要替换的地方。然后使用正则表达式查找这些子字符串,并用所需的值替换它们。