AppDividend
Latest Code Tutorials

Python format() | String Interpolation And Template Strings

0

Python format() method returns a given value into a specified format. The format() method is a higher-level implementation for complex formatting on different objects and strings as well. Python string.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional format.

If you want to format a string, Python format() function is handy.

Python format()

Content Overview

Python 3 introduced a new method to do the string formatting that was also later back-ported to Python 2.7.

This “new style” of string formatting gets rid of the %-operator special syntax and makes the syntax for string formatting more standard.

Formatting is now handled by calling the format() on a string object.

You can use the Python format() to do simple positional formatting, just like you could with “old style” formatting.

Or, you can refer to your variable substitutions by name and use them in any order you want to use.

This is quite the powerful feature as it allows for rearranging the order of display without changing the arguments passed to format().

Python format() method formats the specified value(s) and inserts them inside the string’s placeholder.

The placeholder is defined using the curly brackets: {}.

Read more about the placeholders in the Placeholder section below.

Syntax

format(value[, format_spec])

value: It is that value that to be formatted.

format_spec: Is the format specifier that indicates how the value should be formatted.

This function calls __format__() method of the value object.

We can define the function for our custom classes to use the format() function with them.

Some of the format options for numbers are:

  1. ‘+’ – sign should be used with both the positive and negative numbers.
  2. ‘-‘ – sign should be used only with negative numbers; this is bydefault behavior.
  3. % – multiplied with 100 and shown in percentage.
  4. ‘b’, ‘o’, ‘x’, ‘X’ – convert an integer to binary, octal, and hexadecimal format. The lower case letters will be used for ‘x’ whereas upper case letters will be used with ‘X’. These are applicable only for integers.
  5. ‘e’, ‘E’, ‘f’, ‘F’ – used with floating-point numbers for Exponent notation and Fixed-point notation, respectively.

The format() method returns the formatted string.

Different Types of Format Specifiers in Python

See the following format specifiers.

‘<‘ – Left aligns the result

‘>’ – Right aligns the result

‘^’ – Center aligns the result

‘=’ – Places a sign to the leftmost position

‘+’ – Use the plus sign to indicate if the result is positive or negative

‘-‘ – Use the minus sign for negative values only

‘ ‘ – Use the leading space for positive numbers

‘,’ – Use the comma as a thousands separator

‘_’ – Use an underscore as a thousand separator

‘b’ – Binary format

‘c’ – Converts a value into the corresponding Unicode character

‘d’ – Decimal format

‘e’ – Scientific format, with a lowercase e

‘E’ – Scientific format, with an uppercase E

‘f’ – Fixpoint number format

‘F’ – Fixpoint number format, upper case

‘g’ – General format

‘G’ – General format (using an uppercase E for scientific notations)

‘o’ – Octal format

‘x’ – Hex format, lower case

‘X’ – Hex format, upper case

‘n’ – Number format

‘%’ – Percentage format

See the following code example.

# app.py

# Print a value in integer format
print(format(8918, 'd'))  # 'd' refer to integer format

# Printing a value in float format
print(format(123.5461213, 'f'))  # 'f' refers to float format

# Printing a value in binary format

print(format(12, 'b'))  # 'b' refers to binary

# Hexadecimal format

print(format(20, 'X'))  # 'X' refers to hexadecimal in upper case

Output

➜  pyt python3 app.py
8918
123.546121
1100
14
➜  pyt

So on the above example, we can see that, to format an input into an integer, we have to use ‘d’, in hexadecimal but in the capital letter ‘X’, in binary ‘b’ and for float value we have used ‘f’.

Python format() function for Custom Object

Let’s see how we can use the format() function with the custom objects.

We will create a class and define the __format__() function for it.

This function must return string; otherwise, we will get an error.

See the following code.

# app.py

class App:
    id = 11

    def __init__(self, i):
        self.id = i

    def __format__(self, format_spec):
        print('__format__ method called')
        if format_spec == 's':
            return "App[id=%s]" % self.id
        if format_spec == 'i':
            return str(self.id)
        else:
            return 'invalid format spec'


d = App(21)
print(format(d, 's'))
print(format(d, 'i'))
print(format(d, 'x'))

Output

➜  pyt python3 app.py
__format__ method called
App[id=21]
__format__ method called
21
__format__ method called
invalid format spec
➜  pyt

The formatting operations described here exhibit the variety of quirks that lead to several common errors such as failing to display tuples and dictionaries correctly.

Using the newer formatted string literals or the str.format() interface helps avoid these errors.

These alternatives also provide more robust, flexible, and extensible methods to format the text.

Python String Interpolation / f-Strings

Python 3.6 added the new string formatting way called formatted string literals or “f-strings”.

This new method of formatting strings lets you use the embedded Python expressions inside string constants. Here’s a simple example to give you a feel for the feature.

See the following code example in the Python console.

➜  pyt python3
Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 11
>>> b = 21
>>> f'Eleven plus twenty one is {a + b} and not {2 * (a + b)}.'
'Eleven plus twenty one is 32 and not 64.'
>>>

As you can see, this prefixes the string constant with the letter “f“—hence the name “f-strings.”

This new formatting syntax is powerful. Because you can embed arbitrary Python expressions, you can even do inline arithmetic with it.

Formatted string literals are a Python parser feature that converts f-strings into a series of string constants and expressions. They then get joined up to build the final string.

See the following code.

# app.py

def wish(name, question):
    return f"Happy Birthday, {name}! How's your birthday {question}?"


print(wish('Agent K', 'going'))

Output

➜  pyt python3 app.py
Happy Birthday, Agent K! How's your birthday going?
➜  pyt

Python Template Strings

Let’s see one more tool to format string in Python: template strings. It’s a more straightforward and less powerful mechanism, but in some cases, this might be precisely what you’re looking for.

See the following code.

# app.py

from string import Template

t = Template('Hey, $name!')
formattedString = t.substitute(name='Krunal')
print(formattedString)

Output

➜  pyt python3 app.py
Hey, Krunal!
➜  pyt

You see here that we need to import the Template class from Python’s built-in string module.

Template strings are not a core language feature, but they’re supplied by the string module in the standard library.

Conclusion

There’s more than one way to handle string formatting in Python.

Each method has its pros and cons. Your use case will influence which method you should use.

Finally, Python format() | String Interpolation And Template Strings article is over.

Related Posts

Python time format example

Python string date format example

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.