Appending elements to a multi-line string within a for loop using string interpolation

On Mac, I work with Spyder and run Python 2.7. I have previously used “string.maketrans” without any problems. Now, I need to create a Python file from a multiline string. However, I cannot simply include my list in the “my_list” string interpolation because the data in “some_list” will only work if I add it during the iteration process.

Question:

I have a task labeled as
multiline string
that involves creating a Python file.

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)

It’s not possible to display my list directly on the
string interpolation
as the “some_list” data requires iteration to function. Otherwise,
entire list
will be shown as a simple string.

The desired result is having both “something” from “my_module” and “something2” from “my_module2” imported.

     my_list = [ non_string_iterated_data1,
                 non_string_iterated_data2,
                 non_string_iterated_data3
                ]

What am getting currently is :

    from my_module import something
    from my_module2 import something2
    my_list = [ non_string_iterated_data3 ] # appending only the last element

If the full list is referenced, the resulting output is obtained.

    from my_module import something
    from my_module2 import something2
    my_list = [ "string_data_1", "string_data_2", "string_data_3" ] 


Solution:

Use

.format

my_list = [ 10,11,12]
my_multline = """
       from my_module import something
       from my_module2 import something2
       my_list = {}
       """.format(my_list)

Frequently Asked Questions