-1
  • below code is my valid requirement.
import numpy as np
a =np.array([1, 3, 0, 2], int)
b =np.array([5, 2, 1, 2], int)
print(f'{a > b = }')
  • result is ok
a > b = array([False,  True, False, False])

  • I wanna make inner function which have f-string style.
import numpy as np
a =np.array([1, 3, 0, 2], int)
b =np.array([5, 2, 1, 2], int)

def myprn(text):
    print(f'{text = }')

myprn(a > b)
  • result is not my requirement
  • I wanna print 'a > b' instead of 'text'
text = array([False,  True, False, False])
#^^^ how to fix this requirement?
11
  • Your f-string syntax is wrong. Why do you end your curly brackets with =? Commented Jan 9, 2023 at 12:07
  • 2
    @SimonLundberg this is Python >3.8 Commented Jan 9, 2023 at 12:08
  • 2
    This won't work because a > b is evaluated and saved as text before it is used in the f-string. What to do really depends on your use case. As is, your function does nothing, so you might as well use the print line directly. If the function actually is more complex, you could add a second argument where you pass a descriptive string and print that. Commented Jan 9, 2023 at 12:08
  • 1
    Oh, huh, I didn’t know about that. Been stuck in 3.7 for too long. Commented Jan 9, 2023 at 12:13
  • 1
    @dEitY719 Please see Why is using 'eval' a bad practice? and be sure to read more about eval if you're actually going to use it. As mentioned in another comment, it would help if you gave context of what you're trying to do because solving it this way is not the best... Commented Jan 9, 2023 at 12:20

2 Answers 2

2

You can't, = in f-string is self-documenting sign which just prints expression before it as is. Doc reference

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

Comments

-1

Thanks to @Tomerikoo.

  • His reply gave me a hint. I was able to learn the movements I wanted according to his comments

@Tomerikoo's comment

The only way I can think to make something similar to this work is print(f'{text} = {eval(text)}') and then passing the function strings with the expression, i.e. myprn('a > b')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.