Python f-strings are kinda cool

in #python5 years ago

f strings.png


Python has a number of methods you can use to format strings, so you can include variables in them. I recently started using f-strings and I must admit that I love how they "naturally" fit into the code line.

What do I mean by naturally? Well, they don't interupt the flow. All the other methods add extra stuff to the line of code that's handling this formatting.

Let's say I have four variables, let's call them:

current = 4
total = 20
message = 'log_4.txt'
elapsed = 15

Let's say there is a process that will take about 60 seconds to complete, where it has to process a total of 20 files and display the progress on the terminal.

To have the above state displayed on the terminal, we would need to see something like this (simplified snapshot, to not include a loop):

Processing file 4 of 20 (log_4.txt). Time elapsed: 15 seconds.

To format this in code, without f strings, we could use:

%s and %d formatting:

print('Processing file %d of %d (%s). Time elapsed: %d seconds.' %(current, total, message, elapsed))


.format method:

This is really no different (visually) from %s formatting though.

print('Processing file {} of {} ({}). Time elapsed: {} seconds.'.format(current, total, message, elapsed))


Now, for the fun part...


The slick f-string:

print(f'Processing file {current} of {total} ({message}). Time elapsed: {elapsed} seconds.')


F-strings are a lot neater and more readable. They remind me of string formatting used in Kotlin.

Of course, you can use %f to do %.<number of digits>f to fix decimal digits and other various things; but there are also other ways to enforce that in the code preceding that statement, which might ultimately look better.

I guess all methods have their place. It depends on preference, appropriateness and convenience I would say, but I'll probably be using f-strings more.

Coin Marketplace

STEEM 0.24
TRX 0.19
JST 0.035
BTC 92183.93
ETH 3313.90
USDT 1.00
SBD 3.75