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

149 Views Asked by At

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.

3

There are 3 best solutions below

1
On BEST ANSWER

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.

1
On

You are facing this problem because you didn't use the variable as the argument instead you passed a string.

In simple words, variables are used without quotes.

This will solve the problem prints('Hello? ' + Test)

2
On

Hey there – Suprisingly I've come up with a solution myself which meets my needs!

def prints(druck):
for el in druck.split():
    try:
        print(eval(el), end=" ")
    except:
        print(el, end=" ")

Now I can just type in whatever I want and python will try to run each word of it as code before displaying.

Thank you for your time.