简体   繁体   English

我可以在 string.format 方法中使用 for 循环吗?

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

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?我很困惑为什么格式方法中的 for 循环会失败?

    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.您向file.writelines传递一个生成器表达式,其中每个项目都是一个格式化的字符串。

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.创建 arguments 的生成器表达式,它将被发送 1 次到str.format方法。

Instead, create a generator expression which calls str.format for each item in item_list :相反,为item_list中的每个项目创建一个调用str.format的生成器表达式:

    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.现在file.writelines接收字符串的生成器表达式作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM