pythonprintff-stringself-healing

Automatically turn a string into a formatted string? (Python)


I'd like to program an alternate print() function, that automatically turns the inputted string into a formatted one, with correct formatting for variables.

So why doesn't this work?

Test = 'Hello!'

def prints(druck):
    for el in druck.split():
        print(f'{el}')

prints('Hello? Test')

The output is:

Hello?
Test

I want the output to be:

Hello?
Hello!

At the moment I only put one word into prints(). In the end I want to be able to print variables inside of longer strings without having to {} them.

My dream would be to have a print() function that would check if a word is a variable (something like if el == {el}?) and prints it out correctly, no matter the format.

This is my first question here :) Sorry for any inconveniences! And thanks.


Solution

  • You could use globals().

    def prints(druck):
        for el in druck.split():
            print(globals().get(el, el))
    

    But you should still probably just use normal f-strings for reasons already mentioned in the comments.

    Sorry if I misunderstood the question.