如何在 python 中使用带有变量而不是文本的 .format
How to use .format with a variable rather than text in python
我正在尝试使用 .format(arg1,arg2) 替换字符串变量中的几个占位符,就像我将文字文本定义为 .format 一样,尽管我显然采用了错误的方法因为 .format 看不到占位符。
按字面意思我可能会这样做
var = """ this is a
{0} {1} """.format(colour, animal)
这样就可以了。
我现在已将该模板化文本移动到我已读入的文本文件中,但想在 运行 时替换参数。
请问实现该目标的最佳方法是什么?
var = """this is a {0} {1} """
print(var.format("red", "dog"))
format
是字符串对象的一种方法,对于保存在变量中的字符串和 hard-coded 字符串常量一样有效。
所以你可以有例如:
template.txt
this is a
{0} {1}
并使用它来读取它并替换值:
with open("template.txt") as f:
template = f.read().strip()
colour = "red"
animal = "lion"
print(template.format(colour, animal))
给出:
this is a
red lion
您还可以使用关键字进行替换,这样可以更灵活地安排颜色和动物的顺序(或者实际上,对于同一标记出现多次或根本不出现)。
这是一个模板:
template.txt
This is a {colour} {animal}
使用关键字替换:
with open("template.txt") as f:
template = f.read().strip()
colour = "red"
animal = "lion"
print(template.format(colour=colour, animal=animal))
给出:
This is a red lion
但是现在,举个例子,这是一个适合威尔士语的模板,其中的顺序将被调换:
template.txt
{animal} {colour} ydy hon
现在类似地替换:
print(template.format(colour="goch", animal="draig"))
draig goch ydy hon
您的格式调用在代码中具有其他顺序的项目并不重要,因为它们与相关关键字匹配。
同样,这与您可以使用 hard-coded 字符串常量所做的没有什么不同。
with open("test.txt") as f:
var = f.read().format(colour, animal)
我正在尝试使用 .format(arg1,arg2) 替换字符串变量中的几个占位符,就像我将文字文本定义为 .format 一样,尽管我显然采用了错误的方法因为 .format 看不到占位符。
按字面意思我可能会这样做
var = """ this is a
{0} {1} """.format(colour, animal)
这样就可以了。
我现在已将该模板化文本移动到我已读入的文本文件中,但想在 运行 时替换参数。
请问实现该目标的最佳方法是什么?
var = """this is a {0} {1} """
print(var.format("red", "dog"))
format
是字符串对象的一种方法,对于保存在变量中的字符串和 hard-coded 字符串常量一样有效。
所以你可以有例如:
template.txt
this is a
{0} {1}
并使用它来读取它并替换值:
with open("template.txt") as f:
template = f.read().strip()
colour = "red"
animal = "lion"
print(template.format(colour, animal))
给出:
this is a
red lion
您还可以使用关键字进行替换,这样可以更灵活地安排颜色和动物的顺序(或者实际上,对于同一标记出现多次或根本不出现)。
这是一个模板:
template.txt
This is a {colour} {animal}
使用关键字替换:
with open("template.txt") as f:
template = f.read().strip()
colour = "red"
animal = "lion"
print(template.format(colour=colour, animal=animal))
给出:
This is a red lion
但是现在,举个例子,这是一个适合威尔士语的模板,其中的顺序将被调换:
template.txt
{animal} {colour} ydy hon
现在类似地替换:
print(template.format(colour="goch", animal="draig"))
draig goch ydy hon
您的格式调用在代码中具有其他顺序的项目并不重要,因为它们与相关关键字匹配。
同样,这与您可以使用 hard-coded 字符串常量所做的没有什么不同。
with open("test.txt") as f:
var = f.read().format(colour, animal)