beniiii
beniiii

Reputation: 23

F-string, help on formatting

I'm following a tutorial and trying to understand what happens here. So we are encoding 'message' to bytes first then we take the length of that and align(?) it to the left by 10 and then encode the whole thing?

I'm trying to use this part in my device that doesn't understand f-strings so I need to format it in .format() way instead but can't figure how to do it.

HEADER_LENGTH = 10
message = 'this is test message'

message = message.encode('utf-8')
message_header = f"{len(message):<{HEADER_LENGTH}}".encode('utf-8')

Upvotes: 2

Views: 977

Answers (2)

Oleg Vorobiov
Oleg Vorobiov

Reputation: 512

It's not an fstring after you run your code, both message and message_header are just utf-8 encoded strings.

Upvotes: -1

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140307

you can "downgrade" to format style if your target is prior to Python 3.6

message_header = "{ml:<{hl}}".format(ml=len(message),hl=HEADER_LENGTH).encode('utf-8')

format supports nesting so adaptation is easy. Just move evaluated variables in the format arguments, and use keywords, so placeholding is easier than positional (or empty-brace) style.

The above left-justifies the length of the message (as string) using HEADER_LENGTH length to right-pad with spaces.

Upvotes: 4

Related Questions