paint-brush
1 Minute Read #17 -strings in Python*by@sltrask
3,479 reads
3,479 reads

1 Minute Read #17 -strings in Python*

by Mr TraskDecember 4th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

How long is a piece of string? If it is as long as the many ways to manipulate strings in Python, then it is mighty long indeed. Python 3.6, released in 2016, introduced a whole new way to format strings. Known as ‘formatted-string literals’, they are a much more efficient than anything that preceded them. For example below is a standard way of handling strings using&nbsp;<strong>.format</strong>&nbsp;:
featured image - 1 Minute Read #17 -strings in Python*
Mr Trask HackerNoon profile picture

How long is a piece of string? If it is as long as the many ways to manipulate strings in Python, then it is mighty long indeed. Python 3.6, released in 2016, introduced a whole new way to format strings. Known as ‘formatted-string literals’, they are a much more efficient than anything that preceded them. For example below is a standard way of handling strings using .format :

You can be cute with this, and change the order (the index) in which the variables are called:

Endless fun can be had in this manner…however…there is another way:

Note the use of the (f”Hello…”) here — the f can be capitalised to F(“Hello…”), and it tells Python that you wish to use previously declared variables in this string.

f-strings disturb old-school Pythonistas who have got so very used to the .format method. This is equivalent to moving from a top-loading washing machine to a front-loader. F-strings are just, plainly, better and simpler, and, in speed tests, quite a bit faster in the way they parse. See some slightly more complex code below, using capital F for hopefully more clarity:

You can see that the old .format method is absolutely fine, but it is a tad elongated. The newer f-string manner just scans better for our puny human brains, doing away with the strung-out .format parameters. Here is another example — using multiline strings:

Finally, dictionaries — never easy things to handle in Python, but they do make a good deal more sense using f-strings:

Convinced? If not, hop onto Python 3.6 or 3.7 and give them a couple of days. You will never look back.

*Admittedly this is longer than a ‘1 Minute read’, but f-strings are just worth reading about for more than a minute. I recognise that I have strung this out a bit. Chortle.