w3resource

Python String Formatting

String Formatting

The format() method is used to perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument or the name of a keyword argument.

Syntax:

str.format(*args, **kwargs)

Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

Contents:

Basic formatting:

Example-1:

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

This following statement allows re-arrange the order of display without changing the arguments.

Example-2:

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

Value conversion:

The new-style simple formatter calls by default the __format__() method of an object for its representation. If you just want to render the output of str(...) or repr(...) you can use the !s or !r conversion flags.

In %-style you usually use %s for the string representation but there is %r for a repr(...) conversion.

Setup:

class Data(object):

    def __str__(self):
        return 'str'

    def __repr__(self):
        return 'repr'

Example-1:

class Data(object):

    def __str__(self):
        return 'str'

    def __repr__(self):
        return 'repr'
x='{0!s} {0!r}'.format(Data())
print (x)

Output:

str repr

In Python 3 there exists an additional conversion flag that uses the output of repr(...) but uses ascii(...) instead.

Example-2:

class Data(object):

    def __repr__(self):
        return 'räpr'
x='{0!r} {0!a}'.format(Data())
print(x)

Output:

räpr r\xe4pr

Padding and aligning strings:

A value can be padded to a specific length. See the following examples where the value '15' is encoded as part of the format string.

Note: The padding character can be spaces or a specified character.

Example:

Align right:

>>> '{:>15}'.format('Python')
'         Python'
>>>

Align left:

>>> '{:15}'.format('Python')
'Python         '
>>>

By argument:

In the previous example, the value '15' is encoded as part of the format string. It is also possible to supply such values as an argument.

Example:

>>> '{:<{}s}'.format('Python', 15)
'Python         '
>>>

In the following example we have used '*' as a padding character.

Example:

>>> '{:*<15}'.format('Python')
'Python*********'
>>>

Align center:

Example:

>>> '{:^16}'.format('Python')
'     Python     '
>>>

Truncating long strings:

In the following example, we have truncated ten characters from the left side of a specified string.

Example:

>>> '{:.10}'.format('Python Tutorial')
'Python Tut'
>>>

By argument:

Example:

>>> '{:.{}}'.format('Python Tutorial', 10)
'Python Tut'
>>>

Combining truncating and padding

In the following example, we have combined truncating and padding.

Example:

>>> '{:10.10}'.format('Python')
'Python    '
>>>

Numbers:

Integers:

>>> '{:d}'.format(24)
'24'
>>> 

Floats:

>>> '{:f}'.format(5.12345678123)
'5.123457'
>>>

Padding numbers:

Similar to strings numbers.

Example-1:

>>> '{:5d}'.format(24)
'   24'
>>>

The padding value represents the length of the complete output for floating points. In the following example '{:05.2f}' will display the float using five characters with two digits after the decimal point.

Example-2:

>>> '{:05.2f}'.format(5.12345678123)
'05.12'
>>>

Signed numbers:

By default only negative numbers are prefixed with a sign, but you can display numbers prefixed with the positive sign also.

Example-1:

>>> '{:+d}'.format(24)
'+24'
>>>

You can use a space character to indicate that negative numbers (should be prefixed with a minus symbol) and a leading space should be used for positive numbers.

Example-2:

>>> '{: d}'.format((- 24))
'-24'
>>>

Example-3:

>>> '{: d}'.format(24)
' 24'
>>>

You can control the position of the sign symbol relative to the padding.

Example-4:

>>> '{:=6d}'.format((- 24))
'-   24'
>>>

Named placeholders:

Both formatting styles support named placeholders. Here is an example:

Example-1:

>>> data = {'first': 'Place', 'last': 'Holder!'}
>>> '{first} {last}'.format(**data)
'Place Holder!'
>>> 

.format() method can accept keyword arguments.

Example-2:

>>> '{first} {last}'.format(first='Place', last='Holder!')
'Place Holder!'
>>>

Datetime:

You can format and print datetime object as per your requirement.

Example:

>>> from datetime import datetime
>>> '{:%Y-%m-%d %H:%M}'.format(datetime(2016, 7, 26, 3, 57))
'2016-07-26 03:57'
>>>

Previous: Python String
Next: Python Lists

Test your Python skills with w3resource's quiz



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python/python-format.php