Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23390

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

$
0
0

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')

Viewing all articles
Browse latest Browse all 23390

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>