Can I use a for loop inside the string.format method?

Viewed 100

I am trying to write a list to a file. When I use the following code it gives me an error :

    with open('list.txt', 'w') as fref :
        fref.writelines('{}\n'.format(item for item in item_list))

But when I modify the code to :

    with open('list.txt', 'w') as fref :
        for item in item_list :
            fref.writelines('{}\n'.format(item))

or

when I format the string using % :

    with open('list.txt', 'w') as fref :
        fref.writelines('%s\n' % item for item in item_list)

it works fine. I am confused as to why does the for loop inside the format method fail ?

1 Answers
    with open('list.txt', 'w') as fref :
        fref.writelines('%s\n' % item for item in item_list)

Can be read as (note the parenthesis):

    with open('list.txt', 'w') as fref :
        fref.writelines(('%s\n' % item) for item in item_list)

You pass file.writelines a generator expression, in which each item is a formatted string.

While:

    with open('list.txt', 'w') as fref :
        fref.writelines('{}\n'.format(item for item in item_list))

Creates a generator expression of arguments, that will be sent 1 time to the str.format method.

Instead, create a generator expression which calls str.format for each item in item_list:

    with open('list.txt', 'w') as fref :
        fref.writelines('{}\n'.format(item) for item in item_list)

Now file.writelines receives generator expression of strings as an argument.

Related