Search code examples
pythonpython-3.xstringformatf-string

Pythn 3.6 f-string on pre-formatted string


How can I re-format using f-string this string:

string_from_db = "Hello {full_name}"
full_name = "Mark X"
return f'{string_from_db}'

This example is not working, I have a string which is ready for params injections in the DB, And I want to use python 3.6 f-string on that data.

Thank you


Solution

  • You could use a similar pre f-string approach:

    def my_function():
        string_from_db = "Hello {full_name}"
    
        full_name = "Mark X"
    
        return string_from_db.format(**locals())
    
    print(my_function())
    

    Or a more standard approach:

    def my_function():
        string_from_db = "Hello {full_name}"
    
        full_name = "Mark X"
    
        return string_from_db.format(full_name=full_name)
    
    print(my_function())