Richard Ainsworth
Richard Ainsworth

Reputation: 19

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.

Upvotes: 0

Views: 425

Answers (2)

keepAlive
keepAlive

Reputation: 6665

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())

Upvotes: 1

Lukas Rois
Lukas Rois

Reputation: 81

You can't iterate through an f string. Once the variable in the f string is defined it can't be changed after the next iteration. I would recommend using .format instead.

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

Also don't forget to index the arrays!

Upvotes: 0

Related Questions