Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a compact f-string expression for printing non-str object with space formatting?

Tags:

python

f-string allows a very compact expression for printing str objects with spacing like so:

a = "Hello"
print(f'{a=:>20}')
a=               Hello

Is there a way to do the same for other objects like so:

from pathlib import Path               
b=Path.cwd()
print(f'{b=:>20}')
Traceback (most recent call last):
  File "/usr/lib/python3.10/idlelib/run.py", line 578, in runcode
    exec(code, self.locals)
  File "<pyshell#11>", line 1, in <module>
TypeError: unsupported format string passed to PosixPath.__format__

An alternative is:

print(f'b={str(b):>20}')
b=        /home/user

But this method loses the object info that is shown when I do:

print(f'{b=}')
b=PosixPath('/home/user')

The desired outcome is to print

b=                  PosixPath('/home/user')

Multiple printed statements should show something like:

self.project=       PosixPath('/home/user/project')
self.project_a=     PosixPath('/home/user/project/project')
self.longer=        PosixPath('/home/user/project/project/icons/project/pic.png')
self.PIPFILELOCK=   PosixPath('/home/user/project/Pipfile.lock')
self.VIRTUALENV=    PosixPath('/home/user/.local/share/virtualenvs/project-mKDFEK') 
like image 380
Sun Bear Avatar asked Dec 31 '25 06:12

Sun Bear


1 Answers

You can use !s and !r:

>>> b = Path("/var")
>>> f"{b=!s:>20}"
'b=                /var'
>>> f"{b=!r:>20}"
"b=   PosixPath('/var')"

These are explicit conversion flags.


To tabulate a namespace of keys and values:

>>> d
{'project': PosixPath('/home/user/project'),
 'project_a': PosixPath('/home/user/project/project'),
 'longer': PosixPath('/home/user/project/project/icons/project/pic.png'),
 'PIPFILELOCK': PosixPath('/home/user/project/Pipfile.lock'),
 'VIRTUALENV': PosixPath('/home/user/.local/share/virtualenvs/project-mKDFEK')}
>>> for k, v in d.items():
...     print(f"{k+'=':<14}{v!r}")
... 
project=      PosixPath('/home/user/project')
project_a=    PosixPath('/home/user/project/project')
longer=       PosixPath('/home/user/project/project/icons/project/pic.png')
PIPFILELOCK=  PosixPath('/home/user/project/Pipfile.lock')
VIRTUALENV=   PosixPath('/home/user/.local/share/virtualenvs/project-mKDFEK')

In your example on printing the attributes of a class, just do:

for k, v in self.__dict__.items():
    print(f"self.{k + '=':<14}{v!r}")

Class attributes are already stored in a dictionary that can be accessed from self.__dict__ so you don't have to create d.

Or using 3rd-party tabulate:

>>> from tabulate import tabulate  # pip install tabulate 
>>> d = {k+'=': repr(v) for k,v in d.items()}
>>> print(tabulate(d.items(), tablefmt="plain"))
project=      PosixPath('/home/user/project')
project_a=    PosixPath('/home/user/project/project')
longer=       PosixPath('/home/user/project/project/icons/project/pic.png')
PIPFILELOCK=  PosixPath('/home/user/project/Pipfile.lock')
VIRTUALENV=   PosixPath('/home/user/.local/share/virtualenvs/project-mKDFEK')
like image 93
wim Avatar answered Jan 09 '26 10:01

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!