String Formatting

Strings allow you to hold textual data in Python. Often times, you'll want to print a string and pass in a variable. You can use the format method on strings to pass in a variable.

name = "Dan"
"Hi my name is: {}".format(name)
'Hi my name is: Dan'

A more useful example would be to print grammatically correct English sentences about the data.

In the example below, we want to print the results of the scooter ride data below to easily highlight the data's meaning.

scooter_ride_data = {1: ['4-01-2018', 4.5],
                     2: ['4-01-2018', 3.1],
                     3: ['4-01-2018', 6.2]
                    }

Notice below if we want to pass in several variables, we must provide a numerical counter in the braces {}.

print("Details of today's rides:")
for ride_details in scooter_ride_data.items():
    print("Ride #{0} started on {1} and distance traveled was {2} miles".format(ride_number, start_time, distance_miles))
Details of today's rides:
Ride #3 started on 4-01-2018 and distance traveled was 6.2 miles
Ride #3 started on 4-01-2018 and distance traveled was 6.2 miles
Ride #3 started on 4-01-2018 and distance traveled was 6.2 miles

Basic formatting:

'{} {}'.format('Python', 'Format')
#'Python Format'

'{} {}'.format(10, 30)
# '10 30'

'{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)

# str repr

Example-2:

class Data(object):

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

# 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'

'{: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         '

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

Align center:

Example:

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

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

By argument:

Example:

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

Numbers:

Integers:

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

# float
'{: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'

Last updated