【问题标题】:How to write to the file with a variable .format?如何使用变量 .format 写入文件?
【发布时间】:2023-03-09 17:51:01
【问题描述】:

我想将两个字符串写入一个文件,其间有可变空格。这是我写的代码:

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

但我从中得到ValueError: Invalid conversion specification。我希望它将字符 ab 写入文件,其中一行之间有 6 个空格。

我正在使用 python 2。

【问题讨论】:

  • 请提供更多信息。你期望做什么?编写此代码时您的目标是什么?
  • 我正在尝试将某种格式打印到文件示例 "a b" 中,在这种情况下我想控制单词之间的空格。
  • 请编辑您的问题并添加详细信息,以便每个人在尝试帮助您时都能看到它。

标签: python file python-2.x


【解决方案1】:

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

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

之后的文件内容:

a     b     

【讨论】:

  • 这个很好,谢谢,我认为它非常适合我正在寻找的东西!
【解决方案2】:

我搜索了一下,找到了this。通过一些更改,我编写了这段代码,我尝试并得到了你想要的输出:

width = 6
with open(out_file, 'a') as file:
    f.write("{1:<{0}}{2}\n".format(width, 'a', 'b'))

【讨论】:

    【解决方案3】:

    一个简单的乘法可以在这里工作 (这里重载了乘法运算符)

    width = 6
    charector = ' '
    with open(out_file, 'a') as file:
        file.write('a' + charector * width + 'b')
    

    【讨论】:

      【解决方案4】:

      这有点难看,但你可以这样做。使用{{}},您可以输入文字花括号,然后您可以使用可变宽度格式化格式字符串。

      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)
      

      【讨论】:

      • 这有点困难,因为我实际上有很多行需要不同的空间格式变量,并且这样做需要双倍的行来完成工作。
      • @user1550596 这就是解决方案。您可以定义一个函数,该函数接受 width 和源模式,然后通过将格式化的花括号放入模式中来生成 format_str
      猜你喜欢
      • 2015-06-06
      • 1970-01-01
      • 2013-05-15
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 2020-08-12
      相关资源
      最近更新 更多