Python:文本文件中的占位符变量 [英] Python: Placeholder variables in text file

查看:179
本文介绍了Python:文本文件中的占位符变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为help.txt的文本文件,它将被读取并打印出内容.我需要文件包含变量占位符,用变量占位符替换变量值,例如:'I have 3 variables: {one}, {two} and {three}'

I have a text file called help.txt which will be read and the contents printed out. I need the file to contain variable placeholders where the variable value will be substituted in, eg: 'I have 3 variables: {one}, {two} and {three}'

如果这只是在python文件中硬编码的字符串,我可以将其视为f字符串,但是我不确定如何在外部文件中执行此操作.

If this was just a string hard-coded in the python file I can treat it as an f string but I am unsure how to do this in an external file.

我希望文本在另一个文件中,以便在需要时可以轻松更改它.只有我可以访问代码和文本文件.

I want the text to be in another file so that I can easily change it whenever I need to. Only I will have access to both the code and the text file.

推荐答案

如果我对您的理解正确,则可以在读取文件时检查这些占位符,然后将其替换为变量.鉴于"FileContents"是您用来读取文件的字符串,而"variable"是替换它的变量,只需使用FileContents.replace("{one}", variable)

If I understood you correctly you could just check the file as you read it in for these placeholders and replace them with your variable. Given 'FileContents' is the string you used to read in your file and 'variable' is the variable to replace it with, just use FileContents.replace("{one}", variable)

这篇关于Python:文本文件中的占位符变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆