Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to reuse an f-string as it is possible with a string and format?

I would like to create an f-string that could be used multiple times as the following code with format:

TEXT_AMOUNT = 'text {amount}'


def f1(beginning):
    return beginning + TEXT_AMOUNT.format(amount=10)


def f2(ending):
    return TEXT_AMOUNT.format(amount=100) + ending

How can I achieve the same functionality with using an f-string? I tried:

TEXT_AMOUNT = f'text {amount}'


def f1(beginning):
    amount = 100
    return beginning + TEXT_AMOUNT


def f2(ending):
    amount = 10
    return TEXT_AMOUNT + ending

However, I get the following error:

NameError: name 'amount' is not defined
like image 353
lmiguelvargasf Avatar asked Sep 09 '18 21:09

lmiguelvargasf


1 Answers

You can store it as lambda function:

TEXT_AMOUNT = lambda amount: f'text {amount}'
print(TEXT_AMOUNT(10))

out: 'text 10'
like image 157
Vespertilio Avatar answered Oct 18 '22 08:10

Vespertilio