简体   繁体   中英

Loop within string formatting in Python

I'm trying to learn string formatting in Python and I was wondering if you can do something like this:

print(f'{element[i].key}: {element[i]}\n{element[i].key}:{element[i]}\' for i in range(2))

Basically, I want to run a for loop within a print so I can iterate and print different values within a dictionary. I feel like I have seen something like this before but I have no idea what the name of it is or how to do it.

I think this is what you're after:

my_dict = {'a': 'b', 'c': 'd'}
print('\n'.join(f'{key}: {value}' for key, value in my_dict.items()))

But remember that putting everything on a single line isn't a goal in itself. It's OK to aim for efficiency or performance, but readability and clarity are sometimes even more important.

A basic list comprehension with f-string will do the job:

    [print(f'{key}:{value}') for key, value in my_dict.items()]

Instead of running a for loop within a print, you should put a print inside of a for loop.

For example:

for i in range(2):
    print(f'{element[i].key}: {element[i]}\n{element[i].key}:{element[i]}\')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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