Python string formatting with list

A Quick Guide to Format String in Python

Check out 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 formatting and justifying strings, padding, and aligning 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

Format String, Int, Float, Align, List, Dict in Python

Python Format Function

You can invoke the 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.

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.
>>> '<> <>'.format('Python', 'Format') 'Python Format'

Format Python String

Basic String Formatting

Print a single string using the format function.

Читайте также:  Php closure to string

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.

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.

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.

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

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 justify it.

>>> print(‘ —>’.format(‘Python Programming’)) >>> print(’30> —>’.format(‘Python Programming’)) >>> print(‘ —>’.format(‘Python Programming’)) >>> print(‘ —>’.format(‘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 years of experience and my salary is 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 years of experience and my salary is USD per annum.

Specify Field Width for Numbers

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

>>> 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.

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 20,>> USD per annum.".format(10, 75000)) I've years of experience and my salary is 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.

Format a Number in Octal Style

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.

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(''.format(10)) a >>> >>> >>> print(''.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("".format(1.123456)) 1.123456

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

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

Fixed Point

>>> print(‘Fixed-point example: >’.format(2.2183)) Fixed-point example: >>> print(‘Fixed-point with right alignment example: >’.format(2.2183)) Fixed-point with right alignment example: < 2.218300>>>> print(‘Fixed-point with precision and right alignment example: >’.format(2.2183)) Fixed-point with precision and right alignment example:

General

>>> print(‘General format example: >’.format(2.2183)) General format example: >>> print(‘General format with right alignment example: >’.format(2.2183)) General format with right alignment example: < 2.2183>>>> print(‘General format with precision and center alignment example: >’.format(2.2183)) General format with precision and center alignment example:

Scientific

>>> print(‘Scientific format example: >’.format(2.2183)) Scientific format example: >>> print(‘Scientific format with left alignment example: >’.format(2.2183)) Scientific format with left alignment example: >>> print(‘General format with precision and right alignment example: 25.5e>>’.format(2.2183)) General format with precision and right alignment example:

Format lists and dictionaries

Formatting 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: '.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 Dict in Python

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

>>> print(" Jake's salary is \n Anand's salary is ".format()) Jake's salary is $100K Anand's salary is $120K

You can format dictionary data using the keyworded arguments.

>>> print(" Jake's salary is \n Anand's salary is ".format(sal=)) Jake's salary is $100K Anand's salary is $120K

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.

To Learn Python from Scratch, Read Python Tutorial.

Источник

Оцените статью