F-strings abeg!!!!

Python 3 possesses a lot of nifty new features and one of them is called “f-strings”: formatted string literals.

Here are some of the things f-strings can do as compared to the old way with Python 2.

In Python 2, basic string interpolation is done like this:

>>> print "Hello my name is %s and I am %d years old" %("pystar", 51)
The Python interpreter would print 
"Hello my name is pystar and I am 51 years old"

Python 2 place holders include

%s - string
%d - integer
%f - float

To kick things up a notch, you can perform interpolation by using “format()”:

print "Hello my name is {name} and I am {age} years old".format(name="pystar", age="51")

Python 3 came with a simpler method, so to perform string interpolation in Python 3, you do this:

name = "pystar"
age = 51
print(f"Hello my name is {name} and I am {age} years old")

This method is quite intuitive and makes things much simpler. The only thing that changed is the “f” directive at the beginning of the string literal which tells the Python interpreter what type of string is being evaluated as against “b” for byte strings, “u” for unicode strings and “r” for raw strings.

Python 3 is a pretty decent improvement over Python 2 and f-strings makes any decision to use it in production more reasonable. Another reason to move to Python 3 is the new async/await keywords introduced in Python3.5, this I will be talking about in my next post.