【问题标题】:Python read strings from file, preserving variables to be printedPython 从文件中读取字符串,保留要打印的变量
【发布时间】:2023-04-04 02:46:02
【问题描述】:

我正在制作一个 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")

我想从文件中读取的原因是因为我会有很多不同的字符串,而且它们可能会改变,所以我宁愿不将它们硬编码到程序中(请记住示例字符串非常基本)

谢谢

【问题讨论】:

  • 您能否展示您的代码并解释问题所在

标签: python string list file-io


【解决方案1】:

您可以使用format specification mini-language,然后在显示之前对您的字符串调用.format

strings.txt:

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

main.py:

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

【讨论】:

  • 好吧,所以 format() 有点像“搜索和替换”功能?
【解决方案2】:

在您的文件中使用某些内容来表明需要替换,然后进行这些替换。

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

【讨论】:

  • 哦,当然这是一个错误的做法,我真傻。我可以选择一个字符串然后做你提到的
  • 当 Python 已经有两种不同的值替换字符串方法时,使用正则表达式似乎有点过头了:.format 和百分比运算符
猜你喜欢
  • 1970-01-01
  • 2018-05-09
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 2014-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多