【问题标题】:Using string interpolation to append element in a multi line string under a for loop使用字符串插值在 for 循环下的多行字符串中追加元素
【发布时间】:2020-09-29 13:47:48
【问题描述】:

我有一个多行字符串,它将是需要生成的 python 文件:

for data in some_list:
       my_multline = """

       from my_module import something
       from my_module2 import something2

       my_list = [ %s ]
       """ % (data)

        file.write(my_multiline)

我不能直接在 my_list 字符串插值上表示我的列表,因为“some_list”中的数据只有在我添加迭代流或其他情况下才会起作用。整个列表将表示为纯字符串。

预期输出: 从 my_module 导入一些东西 从 my_module2 导入 something2

     my_list = [ non_string_iterated_data1,
                 non_string_iterated_data2,
                 non_string_iterated_data3
                ]

目前得到的是:

    from my_module import something
    from my_module2 import something2

    my_list = [ non_string_iterated_data3 ] # appending only the last element

如果我参考整个列表,那么得到的输出是:

    from my_module import something
    from my_module2 import something2


    my_list = [ "string_data_1", "string_data_2", "string_data_3" ] 

【问题讨论】:

  • 还有什么问题?
  • 请举例说明,预期输出等
  • @sau 我已经通过添加预期输出进行了编辑,并且输出正在获取。

标签: python string list file string-interpolation


【解决方案1】:

使用.format

my_list = [ 10,11,12]
my_multline = """

       from my_module import something
       from my_module2 import something2

       my_list = {}
       """.format(my_list)

【讨论】:

    猜你喜欢
    • 2020-06-29
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    相关资源
    最近更新 更多