General

Python 3 f-strings

One of my favorite features of Python 3 is f-strings (Formatted String Literals).

Each of these print statements emits the same output. But which of them is the easiest to write and read?

company_name = 'Beeswax'
location = 'New York City'

print('The company {} is based in {}. {} is a great place to work.'.format(company_name, location, location))

print('The company {company_name} is based in {location}. {location} is a great place to work.'.format(company_name=company_name, location=location))

print(f'The company {company_name} is based in {location}. {location} is a great place to work.')

Even if that’s all they did, I’d love f-strings. But they’re much more powerful than that. (For example, you can dereference objects inline: f"Number of connections: {aerospike_client.connection_count}") In fact, you can evaluate arbitrary expressions including function calls within the f-string braces, and all variables in scope can be passed as arguments. See the references below for the details.

References

https://docs.python.org/3.7/reference/lexical_analysis.html#f-strings

Ron

https://www.ronrothman.com/public/about+me.shtml

Recent Posts

Python 3 Rounding Surprise

I discovered this subtle change when one of my unit tests mysteriously failed once I…

5 years ago

Python 3 Exception Chaining

Exception chaining solves two problems in Python 2. 1. Swallowed Exceptions If, while handling exception…

5 years ago

Safe Password Storage – How Websites Get It Wrong

Here's the recording of my talk "15 minutes w/ Beeswax: Safe Password Storage - How…

5 years ago

Python at Scale: Concurrency at Beeswax

My presentation from the NYC Python Meetup: Python at Scale; Concurrency at Beeswax. Concurrent Python…

6 years ago

Python Dependencies The Right Way

My BazelCon 2019 lightning talk, Python Dependencies The Right Way*, has been posted. Please excuse…

6 years ago

mtwsgi: A Multithreaded Python WSGI Implementation

I wanted to combine the simplicity of Python's built-in WSGI server with the benefits of…

12 years ago

This website uses cookies.