Home > Software design >  Python doesn' t update random.choice in (f)-string
Python doesn' t update random.choice in (f)-string

Time:08-25

my python code looks something like this:

import random

numbers = [1, 2, 3, 4]
letters = ["a", "b", "c", "d"]

mix = [f"lalala {random.choice(numbers)} blablabla {random.choice(letters)}"]

for x in range(1, 15):
    print(random.choice(mix))

The problem is that it doesn' t update the random.choice inside of the f string. I have no idea why!

Please help me!

CodePudding user response:

The contents of the f-string are evaluated at the time the f-string is declared; they aren't dynamically re-evaluated each time the f-string is referenced. Putting the f-string inside a random.choice() call doesn't change that; all you're doing is making a choice from a list of one item (the one string with one pre-selected random choice).

If you declare the f-string inside your loop, it will be re-evaluated on each iteration:

for x in range(1, 15):
    print(f"lalala {random.choice(numbers)} blablabla {random.choice(letters)}")
  • Related