Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterator inside f"string

array1=[1, 2, 3]
array2=[0, 1, 2]
a = [10, 20, 30]
b = [100, 200, 300]
padded = ['001', '002', '003']

array1 = iter(array1)
array2 = iter(array2)
a = iter(a)
b = iter(b)
padded = iter(padded)


func= (
    f"  array1 {next(array1)}  \n"
    f" array2 {next(array2)}  \n"
    f" ... a {next(a)}  \n"
    f" ... b {next(b)} \n"
    f" padded {next(padded)} \n"
)

for i in range(2):
    print(func)

Is not iterating.

Wasn’t planning to be learning to code, though here we are. Really appreciate the help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Note that I do not discuss you approach as such. I strictly address your question.


When you do

func = (
    f"  array1 {next(array1)}  \n"
    f" array2 {next(array2)}  \n"
    f" ... a {next(a)}  \n"
    f" ... b {next(b)} \n"
    f" padded {next(padded)} \n"
)

… you have defined func once for all. It is henceforth just a string… for ever…Incidentally, using func to name this string is somehow misleading.

If you want it to be redefined at each iteration, you have to call your nexts again and again… A possible approach* is to turn your variable func into a callable, say, using an anonymous function, as follows:

func = lambda: (
    f"  array1 {next(array1)}  \n"
    f" array2 {next(array2)}  \n"
    f" ... a {next(a)}  \n"
    f" ... b {next(b)} \n"
    f" padded {next(padded)} \n"
)

and then iteratively call it

for i in range(2):
    print(func())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading