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



Python: Tips of the Day

Understanding slice notation:

It's pretty simple really:

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

There is also the step value, which can be used with any of the above:

a[start:stop:step] # start through not past stop, by step

The key point to remember is that the :stop value represents the first value that is not in the selected slice. So, the difference between stop and start is the number of elements selected (if step is 1, the default).

The other feature is that start or stop may be a negative number, which means it counts from the end of the array instead of the beginning. So:

a[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items

Similarly, step may be a negative number:

a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.

Relation to slice() object

The slicing operator [] is actually being used in the above code with a slice() object using the : notation (which is only valid within []), i.e.:

a[start:stop:step]

is equivalent to:

a[slice(start, stop, step)]

Slice objects also behave slightly differently depending on the number of arguments, similarly to range(), i.e. both slice(stop) and slice(start, stop[, step]) are supported. To skip specifying a given argument, one might use None, so that e.g. a[start:] is equivalent to a[slice(start, None)] or a[::-1] is equivalent to a[slice(None, None, -1)].

While the : -based notation is very helpful for simple slicing, the explicit use of slice() objects simplifies the programmatic generation of slicing.

Ref: https://bit.ly/2MHaTp7