1

This will be easier to explain with an example. Let's say I have a settings.py file that looks like this:

settings.py

a_string='This string should contain {value} <<< here.'

I then import settings into my .py file, where I have a function mystring that looks something like this (note the function does not work as I would like it to):

import settings

def mystring(value='100'):
    b_string=f'{settings.a_string}'
    return b_string

print(mystring())
# I would like this to return:
# "This string should contain 100 <<< here."

I have tried placing the f-string formatting inside settings.py, such as:

a_string="f'This string should contain {value} <<< here.'"

to no avail. No luck if I place it in the function or function call either.

I feel like I am missing something obvious, but I just can't see it, so any pointers would be much appreciated.

4
  • 2
    You can't do that with f-strings. They are evaluated at definition time. after a = f'...' is executed, a is as "normal" as any other string Commented Feb 19, 2020 at 14:33
  • @DeepSpace That's true, but in this code, a_string is not an f-string, it's just a regular string containing the literal text {value}. Commented Feb 19, 2020 at 14:53
  • @kaya3 true, but OP specifically asked about doing this with f-string, to which I replied it's impossible (while not considering any hack involving eval or exec) Commented Feb 19, 2020 at 14:55
  • Thanks guys, the question is indeed around f-string, rather than other formatting ways e.g. .format() Commented Feb 19, 2020 at 14:58

1 Answer 1

4

Method 1: use str.format():

b_string=settings.a_string.format(value=value)

Method 2: use eval :

fstr = "the value is {value}"
def func(value=100):
    b_str = eval('f"' + fstr + '"')
    return b_str

WARNING: Only use this method if you know what fstr contains. If fstr is something like "open('virus.txt', 'w').write('evil')", your code gets vulnerable.

Sign up to request clarification or add additional context in comments.

2 Comments

using eval just to arbitrarily be able to use an f-string is hideous and IMHO shouldn't even be listed as a considerable 'solution'
@DeepSpace but its more universal than the first method because you don't have to pass all the values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.