Python 如何使用变量.format写入文件?

Python 如何使用变量.format写入文件?,python,file,python-2.x,Python,File,Python 2.x,我想在一个文件中写入两个字符串,两个字符串之间有可变的空格。以下是我编写的代码: width = 6 with open(out_file, 'a') as file: file.write("{:width}{:width}\n".format('a', 'b')) 但是我从中得到了ValueError:无效的转换规范。我希望它在一行中写入字符a和b,两个字符之间有6个空格 我正在使用python 2。这有点难看,但您可以做到这一点。使用{{}可以键入一个文本大括号,通过它,可以使用

我想在一个文件中写入两个字符串,两个字符串之间有可变的空格。以下是我编写的代码:

width = 6
with open(out_file, 'a') as file:
    file.write("{:width}{:width}\n".format('a', 'b'))
但是我从中得到了
ValueError:无效的转换规范
。我希望它在一行中写入字符a和b,两个字符之间有6个空格


我正在使用python 2。

这有点难看,但您可以做到这一点。使用
{{}
可以键入一个文本大括号,通过它,可以使用可变宽度格式化格式字符串

width = 6

format_str = "{{:{}}}{{:{}}}\n".format(width, width) #This makes the string "{:width}{:width}" with a variable width.


with open(out_file, a) as file:
    file.write(format_str.format('a','b'))
编辑:如果要将这种类型的可变宽度图案应用于代码中使用的任何图案,可以使用以下功能:

import re
def variable_width_pattern(source_pattern, width):
    regex = r"\{(.*?)\}"
    matches = re.findall(regex, source_pattern)
    args = ["{{:{}}}".format(width) for x in range(len(matches))]
    return source_pattern.format(*args)

我在谷歌上搜索了一下,找到了。经过一些修改,我编写了以下代码,并尝试了这些代码,得到了您想要的输出:

width = 6
with open(out_file, 'a') as file:
    f.write("{1:<{0}}{2}\n".format(width, 'a', 'b'))
width=6
将打开的(out_文件,'a')作为文件:

f、 写(“{1:一个简单的乘法将在这里工作 (乘法运算符在此重载)


您需要稍微更改格式字符串,并将
width
作为关键字参数传递给
format()
方法:

width = 6
with open(out_file, 'a') as file:
    file.write("{:{width}}{:{width}}\n".format('a', 'b', width=width))
文件内容:

ab

请提供更多信息。您希望做什么?编写此代码时的目标是什么?我正在尝试将某些格式打印到文件示例“a b”中",word之间的空白是我想在本例中控制的。请编辑您的问题并添加详细信息,以便每个人在试图帮助您时都能看到。这有点困难,因为实际上我有很多行需要不同的空格格式变量,这样做需要双倍的行s来完成这项工作。@user1550596这就是解决方案。您可以定义一个函数,该函数采用
宽度和源模式,然后通过在模式中放置格式化的花括号来生成
格式。\u str
。这个很好,谢谢,我认为它非常适合我所寻找的!
width = 6
with open(out_file, 'a') as file:
    file.write("{:{width}}{:{width}}\n".format('a', 'b', width=width))