George V. Reilly

Python f-strings

At this month’s PuPPy (Puget Sound Pro­gram­ming Python) Meetup, I heard a brief mention of Python f-strings as a new feature coming in Python 3.6.

In essence, they offer a simpler, more versatile method of string formatting and in­ter­po­la­tion over existing methods. F-strings can include not only symbol names but Python ex­pres­sions within strings. With str.format, you can write 'Hello, {name}'.format(name=some_name). You can control various aspects of how name is formatted, such as being centered within a field—see PyFormat and Python String Format Cookbook for ex­am­ples—but no more complex expression is allowed between the braces.

Herewith some examples of f-string ex­pres­sions drawn from PEP 0498:

>>> date = datetime.date(1991, 10, 12)
>>> f'{date} was on a {date:%A}'
'1991-10-12 was on a Saturday'

>>> f'Column={col_idx+1}'
>>> f'number of items: {len(items)}'

>>> f'{extra},waiters:{len(self._waiters)}'
>>> message.append(f" [line {lineno:2d}]")

It looks moderately useful, but—as with any new language feature—it can only be used in brand-new code. Python 3.6 is scheduled to be released in a year’s time, in December 2016. Here’s What’s New in Python 3.6.

blog comments powered by Disqus
Dark Chocolate Gelato-Buttermilk Milkshakes » « Review: The Saxon Tales by Bernard Cornwell