-
PEP 498 - f-strings for Python 3.6
As you know here on CheckiO we are trying to keep Python versions as fresh as possible so now we have Python 3.6 RC1. But let’s get back and see what it actually means for you and which Python 3.6 features you can use in your CheckiO solutions right now.
I want to start a conversation about f-strings (f-literals) and how you can use them in your CheckiO solutions.
The main idea around f-strings is to have a simpler way to format strings in Python. Let me show you what this simplification looks like.
Let’s say you have a set of local variables
>>> import datetime >>> name = 'Fred' >>> age = 50 >>> anniversary = datetime.date(1991, 10, 12)
Now, if you want to combine these variables into one string you would do something like this in Python 3.5:
>>> 'My name is {name}, my age next year is {age}, my anniversary is {anniversary:%A, %B %d, %Y}.'.format(name=name, age=age+1, anniversary=anniversary)
With f-literals you can simplify this since you are using only local variables.
>>> f'My name is {name}, my age next year is {age+1}, my anniversary is {anniversary:%A, %B %d, %Y}.'
As you can see, f-strings provide a better way to include the value of Python expressions inside strings.
Let me show you some other examples that will better explain the basic principles:
1. Multiline expressions
>>> f'''{ … age + 1 … }''' ‘51’
2. You may use expression inside formatting arguments:
>>> val = 1/3 >>> f'Value:{val:10.2}' 'Value: 0.33' >>> precision = 3 >>> f'Value:{val:10.{precision}}' 'Value: 0.333'
3. You can use more complex expressions
>>> ll = [1, 22, 3, 1] >>> big = lambda a:a.capitalize() >>> f'{ll[1]} {big("alex")} {ll.count(1)}' '22 Alex 2'
4. r and f combination in RegExp
>>> header = 'Subject' >>> line = 'Subject: Hi' >>> import re >>> re.match(fr'^{header}: (.*)', line).group(1) 'Hi'
These are the most basic things you need to know about f-strings so you can understand all the benefits and use them in your CheckiO solutions. I’m sure solutions with f-strings will get a bit more up-votes because it makes them more readable.
In PEP 498 - Literal String Interpolation (Author: Eric V. Smith) you can learn about escape sequences, error handling, using lambdas inside f-strings and many more.
- Alex
Welcome to CheckiO - games for coders where you can improve your codings skills.
The main idea behind these games is to give you the opportunity to learn by exchanging experience with the rest of the community. Every day we are trying to find interesting solutions for you to help you become a better coder.
Join the Game