Python String format()

Filed Under: Python

Python String format() function is used to create a formatted string from the template string and the supplied values.

Python String format()

Python String format() function syntax is:


str.format(*args, **kwargs)
  • The template string can be a string literal or it can contains replacement fields using {} as delimiter.
  • The replacement field can be a numeric index of the arguments provided, or they can be keyword based arguments.
  • If the replacement fields have no index or keyword value, then they are replaced based on index and in order i.e. 0,1,…,n.
  • We can provide sequences such as tuple and list as argument for index based replacement.
  • We can provide dictionary as argument for keyword based replacements.
  • The format function argument can be an object too, we can access its attributes using dot operator for replacement field.
  • We can create a specified length string using format() function with the string literal right, left or center aligned. We can also specify the character to use for padding, default is white space.
  • String format() function provides a lot of features to format numbers. For example, base conversion from decimal to octal, hex etc. We can also perform percentage, padding etc.
  • There are shortcut ways to call __str__() and __repr__() functions on an argument using !s and !r.

Python String format() Examples

Let’s look at some examples of using format() function.

Simple Index Based Formatting


print("My Name is {0}".format("Pankaj"))

print("I like {0} and {1}".format("Java", "Python"))
# same as above
print("I like {} and {}".format("Java", "Python"))

# index can be in any order
print("I like {1} and {0}".format("Java", "Python"))

Output:


My Name is Pankaj
I like Java and Python
I like Java and Python
I like Python and Java

Sequences as format() argument


# unpacking from sequences
t = ("Java", "Python")
print("I like {1} and {0}".format(*t))

l = ["Java", "Python"]
print("I like {} and {}".format(*t))

Output:


I like Python and Java
I like Java and Python

Keyword arguments in format()


print("{name} is the {job} of {company}".format(name="Pankaj", job="CEO", company="JournalDev"))

Output: Pankaj is the CEO of JournalDev

Dictionary as format() argument

We can use dictionary in format() function argument for keyword based field replacements.


d = {"name": "Pankaj", "job": "CEO", "company": "JournalDev"}
print("{company} {job} is {name}".format(**d))

Output: JournalDev CEO is Pankaj

Accessing Object attributes for field replacement

We can pass an object in format() method and use the dot operator to access its attributes for field replacement.


class Data:
    id = 0
    name = ''

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


dt = Data(1, 'Test')

print("{obj_name} id is {obj.id} and name is {obj.name}".format(obj_name="Data", obj=dt))

Output: Data id is 1 and name is Test

Formatted String with padding and alignment

We can create a string of specified length using format() method. By default, it will be left aligned and white spaces will be used for padding. However, we can specify character to use for padding and alignment for source string.


>>> "{:^30}".format("data center aligned")
'     data center aligned      '

>>> "{:30}".format("data without align")
'data without align            '

>>> "{:<30}".format("data left aligned")
'data left aligned             '

>>> "{:>30}".format("data right aligned")
'            data right aligned'

>>> "{:^30}".format("data center aligned")
'     data center aligned      '

>>> "{:|^30}".format("data with fill character")
'|||data with fill character|||'

I am using Python console for this example so that you can see the white spaces padding in the string. If we use print() function here, the quotes around the string will be not shown and string length will not be clear.

String format() with numbers

There are many formatting options for numbers, let's look at some of them.

Specifying a sign (+, -) for formatted string


print('{:+f}; {:+f}'.format(1.23, -1.23))
print('{: f}; {: f}'.format(1.23, -1.23))
print('{:-f}; {:-f}'.format(1.23, -1.23))

Output:


+1.230000; -1.230000
 1.230000; -1.230000
1.230000; -1.230000

Notice that in the second statement, whitespace is being used as the prefix for the number. For negative numbers, minus (-) sign is used always.

Format integers to different bases

We can easily convert an int to different bases, such as hexadecimal, octal, binary etc. We can also specify whether the formatted string will contain the prefixes for the base or not.


print("int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(28))
print("int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(0x1c))
print("int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(28))

Output:


int: 28;  hex: 1c;  oct: 34;  bin: 11100
int: 28;  hex: 1c;  oct: 34;  bin: 11100
int: 28;  hex: 0x1c;  oct: 0o34;  bin: 0b11100

format() with complex number


complex_number = 4 + 2j
print("Real: {0.real}, Imaginary: {0.imag}".format(complex_number))

Output: Real: 4.0, Imaginary: 2.0

It's just like accessing attributes of an object.

Formatting numbers using comma as a thousands separator


print('{:,}'.format(1234567890))

Output: 1,234,567,890

Percentage, Padding and Rounding


print('Percentage: {:.3%}'.format(19 / 28))
print('{0:7.2f}'.format(2.344))
print('{0:10.2f}'.format(22222.346))

Output:


Percentage: 67.857%
   2.34
  22222.35

Note that rounding after decimal places are done as per the default rounding rules. Also, the padding is done in front of the number.

Calling str() and repr() functions

We can call str() and repr() functions easily for an object using !s and !r respectively.


print("With Quotes: {0!r}, Without Quotes: {0!s}".format("Data"))


class Test:

    def __str__(self):
        return 'test str'

    def __repr__(self):
        return 'test repr'


print("Test Representation: {0!r}, Test String Representation: {0!s}".format(Test()))

Output:


With Quotes: 'Data', Without Quotes: Data
Test Representation: test repr, Test String Representation: test str

Summary

Python String format() method is very powerful in creating a string from different kinds of input sources and apply the formatting rules. It's far better than earlier % based formatting and template strings. However, if you are using Python 3.6+, you should also look at f-string formatting (PEP 498 -- Literal String Interpolation).

Reference: API Doc

You can checkout complete python script and more Python examples from our GitHub Repository.

Comments

  1. kirenpillay1@gmail.com says:

    Somethings wrong with your page, I don’t see the raw format strings.

    1. Pankaj says:

      I didn’t get what you mean, I can see all the code snippets properly. Can you please try to clear your browser cookie/cache and try again?

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages