Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Is there a shorthand for [eg]: print(f'type(var) = {type(var)}')

Is there a shorthand in Python for (e.g.) print(f'type(var) = {type(var)}'), without having to state the object in the text and the {.}?

The short answer may be "no", but I had to ask!

E.g. in SAS one may use &= to output a macro variable and its value to the log...

%let macrovar = foobar;  
%put &=macrovar;

which returns in the log: MACROVAR = foobar

This is my first question, and I found it difficult to search for an answer, so apologies if it's been asked and answered.

like image 802
Daniel Thomas Avatar asked Sep 01 '21 15:09

Daniel Thomas


People also ask

What is print F in Python?

Python print() Function The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.

How do you print a variable type in Python?

How to Print the Type of a Variable in Python. To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

What is %d and %f in Python?

Answer. In Python, string formatters are essentially placeholders that let us pass in different values into some formatted string. The %d formatter is used to input decimal values, or whole numbers. If you provide a float value, it will convert it to a whole number, by truncating the values after the decimal point.

How do you print variable names and values in Python?

Using f-strings in Python to print variables is the most commonly used method and I would personally recommend using this method. In this method, an 'f' is placed before the opening quotation mark of a string. Braces {} are placed around the names of variables that you are looking to print.


1 Answers

Indeed there is. As of python 3.8, you can simply type f'{type(var)=}', and you will get the output you desire:

>>> x = {}
>>> f'{x=}'
'x={}'
>>> f'{type(x)=}'
"type(x)=<class 'dict'>"

Further reading:

  1. The "What's New In Python 3.8" page
  2. The documentation for f-strings
  3. The discussion on BPO that led to this feature being implemented.
like image 106
Alex Waygood Avatar answered Nov 14 '22 23:11

Alex Waygood