A Quick Guide to Format String in Python

A Quick Guide to Format String in Python

In this tutorial to know how to format string and other data types in Python using the format function. You’ll also see several examples such as format and justify strings, padding and align numbers to adjust the print output.

In this tutorial to know how to format string and other data types in Python using the format function. You’ll also see several examples such as format and justify strings, padding and align numbers to adjust the print output.

Let’s first see how to use the Python format() function with strings.

Python Format – String and Other Types
  • 1 Python format function
    1.1 Single argument formatting1.2 Multiple arguments formatting* 2 Format a Python string
    2.1 Basic string formatting2.2 Padding and align strings2.3 Justify a variable string expansion* 3 Format integers
    3.1 Using separator number formatting3.2 Specify field width for numbers3.3 Padding for numbers3.4 Format a number as binary3.5 Format a number as octal3.6 Format a number as hex* 4 Representing a float number
    4.1 Simple example4.2 Fixed point4.3 General4.4 Scientific* 5 Format lists and dictionaries
    5.1 Formatting a list in Python5.2 Formatting a dict in Python

Here are a few of the simple examples of the Python string formatting.

Python format function

You can invoke format function in one of the following ways:

Single argument formatting

The simplest case while calling the Python format function is to have a single formatter. Below is the syntax to use it.

Format syntax : '{}'.format(param)

* Description:
** '{}': It is the format target, i.e., the placeholder.
** param: It can be a string, integer, float, or any of the collection types.
** Return: It returns a formatted output with the input argument substituting the placeholder.

See a quick illustration:

>>> '{}'.format('Formatting a String in Python')
'Formatting a String in Python'

Multiple arguments formatting

A slightly complicated way to call the Python format function is to supply more than one formatter at a time. Below is the syntax to use it.

Format syntax : '{} {}'.format(arg1, arg2)

* Description:
** '{} {}': We can have multiple placeholders.
** arg1, arg2: They can be a string, integer, float, or any of the collection types.
** Return: It returns a formatted output with the input argument substituting the placeholder.

See a quick illustration:

>>> '{} {}'.format('Python', 'Format')
'Python Format'

Format a Python string

Basic string formatting

Print a single string using the format function.

>>> test = "Hello"
>>> print('{}'.format(test))
Hello

Combine two string literals and print them using the format function.

>>> first = "Hello"
>>> second = "World"
>>> print('{} {}'.format(first, second))
Hello World

Padding and align strings

We can also use the Python format function to allow padding.

Its purpose is to align a string either using a space or some value. You need to provide the length for the alignment which should be higher than the size of the target string.

It is because the alignment can only occur in a box of fixed length.

Let’s align a string to the right with spaces.

>>> print(format("Hello", ">10s"))
     Hello

Now, let’s do the same operation using the ‘#’ character.

>>> print(format("Hello", "#>10s"))
#####Hello

Here is a brief description of the above steps.

  • You can see that the box length for printing the string is 10.
  • It means the max we can accommodate the ten characters.
  • The word “Hello” itself has five letters and the ‘#’ gets filled at the remaining five places.
  • You might have observed the “>” symbol in the format syntax. It makes our target string to move to the right side.

If you like to align the target string from the left, then use the ‘<‘ symbol.

>>> print(format("Hello", "#<10s"))
Hello#####

You can even make a string center-aligned inside a fixed-length box.

>>> print(format("Hello", "#^15s"))
#####Hello#####

The carat ‘^’ sign makes the string format to the center.

Justify a variable string expansion

In the below example, we demonstrate the variable string expansion and justifies it.

>>> print('<-- {0:30} -->'.format('Python Programming'))
<-- Python Programming             -->
>>> print('<-- {0:>30} -->'.format('Python Programming'))
<--             Python Programming -->
>>> print('<-- {0:<30} -->'.format('Python Programming'))
<-- Python Programming             -->
>>> print('<-- {0:^30} -->'.format('Python Programming'))
<--       Python Programming       -->

Format integers

There are many ways to format an Integer, let’s see the basic usage first.

>>> print("I've <{}> years of experience and my salary is <{}> USD per annum.".format(10, 75000))
I've <10> years of experience and my salary is <75000> USD per annum.

Using separator number formatting

It is a standard convention to display the salary with commas. Python format function supports this representation and requires a pair of ‘:’ and ‘,’ inside the parenthesis.

>>> print("I've <{}> years of experience and my salary is <{:,}> USD per annum.".format(10, 75000))
I've <10> years of experience and my salary is <75,000> USD per annum.

Specify field width for numbers

Same as we did for strings is applicable for the integers. For integers, we can’t use precision.

>>> print("I've <{:5}> years of experience and my salary is <{:15,}> USD per annum.".format(10, 75000))
I've <   10> years of experience and my salary is <         75,000> USD per annum.

Padding for numbers

While specifying the width for integers, you can use a character for padding the space left vacant after printing the subject.

>>> print("I've <{:#>8}> years of experience and my salary is <{:z>20,}> USD per annum.".format(10, 75000))
I've <######10> years of experience and my salary is <zzzzzzzzzzzzzz75,000> USD per annum.

Format a number as binary

Python format function allows printing a number in binary style. The symbol ‘b’ after the colon inside the parenthesis notifies to display a number in binary format.

>>> print('{0:b}'.format(10))
1010

Format a number as octal

Python format function allows printing an integer in the octal style. The symbol ‘o’ after the colon inside the parenthesis notifies to display a number in octal format.

>>> print('{0:o}'.format(10))
12

Format a number as hex

Python format function allows printing an integer in the hex style. The symbol ‘x’ or ‘X’ after the colon inside the parenthesis notifies to display a number in hex format.

>>> print('{0:x}'.format(10))
a
>>> 
>>> 
>>> print('{0:X}'.format(10))
A

Representing a float number

A float data type also has a couple of variations which you can style using the Python format function.

Simple example

Let’s print a full floating point number.

>>> print("{0:f}".format(1.123456))
1.123456

Now, let’s print a floating point number truncating after three decimal points.

>>> print("{0:.3f}".format(1.123456))
1.123

Finally, let’s print a floating point number which truncates after three decimal places but does round the final value.

>>> print("{0:.3f}".format(1.123556))
1.124

Fixed point

>>> print('Fixed-point example: <{0:f}>'.format(2.2183))
Fixed-point example: <2.218300>
>>> print('Fixed-point with right alignment example: <{0:25f}>'.format(2.2183))
Fixed-point with right alignment example: <                 2.218300>
>>> print('Fixed-point with precision and right alignment example: <{0:<25.10f}>'.format(2.2183))
Fixed-point with precision and right alignment example: <2.2183000000             >

General

>>> print('General format example: <{0:g}>'.format(2.2183))
General format example: <2.2183>
>>> print('General format with right alignment example: <{0:25g}>'.format(2.2183))
General format with right alignment example: <                   2.2183>
>>> print('General format with precision and center alignment example: <{0:^25.10g}>'.format(2.2183))
General format with precision and center alignment example: <         2.2183          >

Scientific

>>> print('Scientific format example: <{0:e}>'.format(2.2183))
Scientific format example: <2.218300e+00>
>>> print('Scientific format with left alignment example: <{0:<25e}>'.format(2.2183))
Scientific format with left alignment example: <2.218300e+00             >
>>> print('General format with precision and right alignment example: <{0:>25.5e}>'.format(2.2183))
General format with precision and right alignment example: <              2.21830e+00>

Format lists and dictionaries

Formatting a list in Python

The Python format method accepts a sequence of positional parameters. If we pass an array or a List, then let’s find out the result.

>>> langs = ['C', 'C++', 'CSharp']
>>> print('Skillset: {}'.format(langs))
Skillset: ['C', 'C++', 'CSharp']

The whole list gets displayed. You can also decide to print one item from the sequence by providing its index.

>>> print('Skillset: {0[1]}'.format(langs))
Skillset: C++

You can even send the list item as the positional parameters. To achieve this, unpack them using the * operator.

>>> print('Skillset: {}'.format(*langs))
Skillset: C

Formatting a dict in Python

Format function allows using a dictionary as a parameter. See the below example.

>>> print(" Jake's salary is {0[jake]} \n Anand's salary is {0[anand]}".format({'jake': '>>> print(" Jake's salary is {0[jake]} \n Anand's salary is {0[anand]}".format({'jake': '$100K', 'anand': '$120K'}))
Jake's salary is $100K 
Anand's salary is $120K
00K', 'anand': '>>> print(" Jake's salary is {0[jake]} \n Anand's salary is {0[anand]}".format({'jake': '$100K', 'anand': '$120K'}))
Jake's salary is $100K 
Anand's salary is $120K
20K'}))
Jake's salary is >>> print(" Jake's salary is {0[jake]} \n Anand's salary is {0[anand]}".format({'jake': '$100K', 'anand': '$120K'}))
Jake's salary is $100K 
Anand's salary is $120K
00K 
Anand's salary is >>> print(" Jake's salary is {0[jake]} \n Anand's salary is {0[anand]}".format({'jake': '$100K', 'anand': '$120K'}))
Jake's salary is $100K 
Anand's salary is $120K
20K

You can format dictionary data using the keyworded arguments.

>>> print(" Jake's salary is {sal[jake]} \n Anand's salary is {sal[anand]}".format(sal={'jake': '>>> print(" Jake's salary is {sal[jake]} \n Anand's salary is {sal[anand]}".format(sal={'jake': '$100K', 'anand': '$120K'}))
Jake's salary is $100K 
Anand's salary is $120K
00K', 'anand': '>>> print(" Jake's salary is {sal[jake]} \n Anand's salary is {sal[anand]}".format(sal={'jake': '$100K', 'anand': '$120K'}))
Jake's salary is $100K 
Anand's salary is $120K
20K'}))
Jake's salary is >>> print(" Jake's salary is {sal[jake]} \n Anand's salary is {sal[anand]}".format(sal={'jake': '$100K', 'anand': '$120K'}))
Jake's salary is $100K 
Anand's salary is $120K
00K 
Anand's salary is >>> print(" Jake's salary is {sal[jake]} \n Anand's salary is {sal[anand]}".format(sal={'jake': '$100K', 'anand': '$120K'}))
Jake's salary is $100K 
Anand's salary is $120K
20K

There can be more complex usages of the Python format function which you can face in your work environments. Please do let us know if you like to add one of them here.

Thanks for reading ❤

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: