Python 3's f-Strings: Usage Guide

Python 3's f-Strings: Usage Guide

Python 3's f-Strings - A complete guide to the most well received feature of Python 3

Python F String

Python’s F String was launched with Python 3.6.0 by PEP-498 – Literal String Interpolation and was called python f strings in layman’s language.Before the introduction of Python f strings, there were other methods of formatting like %-formatting , str.format() or string.Template(). All these methods have their advantages and disadvantages but were very difficult to use. But Python f strings have become the most popular feature of Python.

%-formatting

Before the advent of f-strings in Python, %-formatting was used, which can only format integers, strings and doubles. Any other type will either not be supported or converted into one of these. One of the major issues which it faces is that it encounters an error if more than one value is provided. This is well documented in official documentation of Python f string

>>> msg = 'disk failure'
>>> 'error: %s' % msg
'error: disk failure'
If message is a tuple

>>> msg = ('disk failure', 32)
>>> 'error: %s' % msg
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

To be defensive, you can pass more than one value like this

>>> 'error: %s' % (msg,)
"error: ('disk failure', 32)"

str.format()

This method addresses many issues of %-formatting as in supporting multiple parameters which could be further extended using format(). The major issue with it is verbosity. Have a look at the following code, the ‘name’ is used for so many times.:-

>>> name = "Saral"
>>> 'My name is {name}.'.format(name = name)
'My name is Saral.'
>>>

However, you can use the simpler method to overcome this:-

>>> name = "Saral"
>>> 'My name is {}.'.format(name)
'My name is Saral.'
>>>

But,this case is simpler and easy to read, only if we have fewer placeholders {} and variables. If the number of placeholders increases, we will have to go back to the placeholder and variable over and again to be correct.

Python f-strings

Python’s f strings overcome the majority of the issues discussed above. Therefore the current versions of Python (Python 3.6 and above) come with Python f-strings. It uses minimal syntax and is more convenient and readable than any of the other methods.

How to use f-strings in Python

To use Python f-strings he common practice (as detailed in the official documentation ) is to use f followed by ‘(Opening single quote) , text if any, variable in {} (single curly brackets) and ‘ (Closing single quote).

f '<text> {variable} <text> .....'

Have a look at the following example

name = "Saral"
Age = 30

print (f'My name is {name} and I am {age} years old.')

Output

My name is Saral and I am 30 years old.

Using methods, functions and calculations in Python f-strings

You can directly do the calculations inside a f-string and can even use methods and functions.

Calculations:

>>> f'8 and 10 are {8 + 10}.'
'8 and 10 are 18.'
>>>

Methods:

name = 'saral'
>>> f'My name is {name.upper()}.'
'My name is SARAL.'
>>>

Functions:

>>> def foo():
...    return 10
>>> f'result is {foo()}.'
'result is 20.'
>>>
Python f strings - Escape Sequences

If you have done formatting in Python, you must know that escape character comes handy. However, f-strings do not support the escape character inside the expression portion.It means that f-string expression part can not inclued a backslash.

>>> f'Text in {'single quotes'}.'
  File "<stdin>", line 1
   f'Text in {'single quotes'}.'
                    ^
SyntaxError: invalid syntax
>>> f'Text in {'single quotes'}.'
 File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash
>>>

In this case, we will have to use different quotes inside the expression:-

>>> f'Text in {"double quotes"}.'
'Text in double quotes.'
>>>

However, backslash (escape character) is allowed in the string portion of the text.

f'String portion's backslash are allowed {"hurray"}.'
"String portion's backslash are allowed hurray."
Python f stings - Inline comments

Just like backslashes, you can not use inline comments inside the expression portion of the Python F string.

>>> f'Saral is {6 * 5 #age}'
 File "<stdin>", line 1
SyntaxError: f-string expression part cannot include '#'
>>>
Printing braces using Python F-strings

If you want to print braces using the Python F-strings. You must use two braces to print single brace and 4 braces to print double braces.

>>> f'{{"Single Braces"}}'
'{"Single Braces"}'
>>> f'{{{"This will also print Single Braces"}}}'
'{This will also print Single Braces}'
>>> f'{{{{"This will print Double Braces"}}}}'
'{{"This will print Double Braces"}}'
>>>
Python f-stings - Working with dictionaries

Since dictionaries involve quotes, using them inside f-strings could be a bit tricky.

>>> details = {'name': 'saral', 'age' : 30}

If you use single quotes

>>> f'My name is {details['name'] and I am {details['age'].'
 File "<stdin>", line 1
   f'My name is {details['name'] and I am {details['age'].'
                             ^
SyntaxError: invalid syntax

If you try using backslash

>>> f'My name is {details['name'] and I am {details['age'].'
 File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash

The best way is to use different kind of quotes than outside (i.e. double quotes)

>>> f'My name is {details["name"]} and I am {details["age"]}.'
'My name is saral and I am 30.'

Python f-strings- Specifying formats

Using the f-strings in Python, we can specify the formats like zero-padding a number, digits after decimal or datetime. This is also called f-strings padding in Python.

For example, we can have an number with 0 padding using F-strings like this:-

>>> for n in range(1,11):
...     print(f'The number is {n:02}')
...
The number is 01
The number is 02
The number is 03
The number is 04
The number is 05
The number is 06
The number is 07
The number is 08
The number is 09
The number is 10
>>>

Similarly, we can define the number of digits after decimal in a float. This doesn’t just strip off the rest of the decimal points, but round it properly.

>>> from math import pi
>>> print(f'The value of pi is {pi:.4f}')
The value of pi is 3.1416
>>>

We can format the dates using datetime module in Python f-strings also:

>>> import datetime
>>> date = datetime.date(1991, 10, 12)
>>> f'{date} was on a {date:%A}'
'1991-10-12 was on a Saturday'
>>>f'The date is {date:%A, %B %d, %Y}.'
>>>'The date is Saturday, October 12, 1991.'

You can find more directives (i.e. %A etc.) from here.

Raw f-strings in Python

We can also print the raw strings as under:-

>>> name = 'Fred'
>>> f'He said his name is {name!r}.'
"He said his name is 'Fred'."
Multi-line f-strings in Python

We can also use multiline strings as shown below. You must note that you need to add f in front of every line otherwise you will get an error.

>>> name = 'Saral'
>>> age = 30
>>> profession = "Pythonista"
>>> sentence = (
...    f'My Name is {name}.'
...     f'I am {age} years old.'
...    f'I am a {profession}.'
... )
>>> sentence
'My Name is Saral.I am 30 years old.I am a Pythonista.'
>>>

So, just dive into it and start practicing Python f-strings.

Originally published at https://saralgyaan.com

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

☞  A Complete Machine Learning Project Walk-Through in Python

☞  Python Tutorial - Python GUI Programming - Python GUI Examples (Tkinter Tutorial)

☞ Python Tutorial: Image processing with Python (Using OpenCV)



Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Description
Learn Hands-On Python Programming By Creating Projects, GUIs and Graphics

Python is a dynamic modern object -oriented programming language
It is easy to learn and can be used to do a lot of things both big and small
Python is what is referred to as a high level language
Python is used in the industry for things like embedded software, web development, desktop applications, and even mobile apps!
SQL-Lite allows your applications to become even more powerful by storing, retrieving, and filtering through large data sets easily
If you want to learn to code, Python GUIs are the best way to start!

I designed this programming course to be easily understood by absolute beginners and young people. We start with basic Python programming concepts. Reinforce the same by developing Project and GUIs.

Why Python?

The Python coding language integrates well with other platforms – and runs on virtually all modern devices. If you’re new to coding, you can easily learn the basics in this fast and powerful coding environment. If you have experience with other computer languages, you’ll find Python simple and straightforward. This OSI-approved open-source language allows free use and distribution – even commercial distribution.

When and how do I start a career as a Python programmer?

In an independent third party survey, it has been revealed that the Python programming language is currently the most popular language for data scientists worldwide. This claim is substantiated by the Institute of Electrical and Electronic Engineers, which tracks programming languages by popularity. According to them, Python is the second most popular programming language this year for development on the web after Java.

Python Job Profiles
Software Engineer
Research Analyst
Data Analyst
Data Scientist
Software Developer
Python Salary

The median total pay for Python jobs in California, United States is $74,410, for a professional with one year of experience
Below are graphs depicting average Python salary by city
The first chart depicts average salary for a Python professional with one year of experience and the second chart depicts the average salaries by years of experience
Who Uses Python?

This course gives you a solid set of skills in one of today’s top programming languages. Today’s biggest companies (and smartest startups) use Python, including Google, Facebook, Instagram, Amazon, IBM, and NASA. Python is increasingly being used for scientific computations and data analysis
Take this course today and learn the skills you need to rub shoulders with today’s tech industry giants. Have fun, create and control intriguing and interactive Python GUIs, and enjoy a bright future! Best of Luck
Who is the target audience?

Anyone who wants to learn to code
For Complete Programming Beginners
For People New to Python
This course was designed for students with little to no programming experience
People interested in building Projects
Anyone looking to start with Python GUI development
Basic knowledge
Access to a computer
Download Python (FREE)
Should have an interest in programming
Interest in learning Python programming
Install Python 3.6 on your computer
What will you learn
Build Python Graphical User Interfaces(GUI) with Tkinter
Be able to use the in-built Python modules for their own projects
Use programming fundamentals to build a calculator
Use advanced Python concepts to code
Build Your GUI in Python programming
Use programming fundamentals to build a Project
Signup Login & Registration Programs
Quizzes
Assignments
Job Interview Preparation Questions
& Much More

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more: