-1

With the following code i can interpolate a string within a limit length:

HEADER_LENGTH = 10
message = "Hello"

header = f"{len(message):<{HEADER_LENGTH}}"

That way header is a string with max_length = 10

So the return of the code will be:

#print(header)
>>> 5

#print(len(header))
>>> 10

I'm trying to do something like this:

HEADER_LENGTH = 10
message = "Hello"
word = "foo"

#just example it doesn't work
header = f"{{word} {len(message)}}:<{HEADER_LENGTH}"

And the expected output will be:

#print(header)
>>> foo 5

#print(len(header))
>>> 10
  • There are any way to do this using f string?
  • If not, how can I achieve this?
Shinforinpola
  • 200
  • 1
  • 15

1 Answers1

2

Yes, you can nest f-strings. In your case you want this:

header = f"{f'{word} {len(message)}':<{HEADER_LENGTH}}"

But I would caution against putting too much complexity into an f-string. It would be clearer if written separately:

part1 = f'{word} {len(message)}'
header = f"{part1:<{HEADER_LENGTH}}"
John Zwinck
  • 239,568
  • 38
  • 324
  • 436