简体   繁体   中英

Specifying width of concatenated variables in a f-string

I'm using the loguru package for logging in my python project.

https://github.com/Delgan/loguru

I'm looking to override the default format so I can specify a fixed with for the module / function / line number string.

Here's the default format...

'<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>'

The output is something like this...

2020-12-28 14:36:27.510 | INFO     | package1.module1:function:132 - Listing Users...
2020-12-28 14:36:27.601 | ERROR    | package10.module10:function10:1000 - The provided token has expired

I want to add a static width/padding to the package/module/function so the output looks like...

2020-12-28 14:36:27.510 | INFO     | package1.module1:function:132      - Listing Users...
2020-12-28 14:36:27.601 | ERROR    | package10.module10:function10:1000 - The provided token has expired

The problem is the full path with function line number is constructed from 3 variables...

<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan>

Is there any way I can specify a width for the combination of the strings? Something like...

<cyan>{name + ":" + function + ":" + line : 45}</cyan>

Appreciate the help!

You can always limit string length, just like you would do with any sequence :

# 150 chars string:
x = "abc" * 50

# 30 chars string:
y = "xyz" * 10

# predefined display limit:
n = 45

spaces = " " * n
print(f"{(x+spaces)[:n]} end line")
print(f"{(y+spaces)[:n]} end line")
print(f"{(y+x+spaces)[:n]} end line")

Outputs:

abcabcabcabcabcabcabcabcabcabcabcabcabcabcabc end line
xyzxyzxyzxyzxyzxyzxyzxyzxyzxyz                end line
xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzabcabcabcabcabc end line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM