Format Specifier

What is a Format Specifier?

A format specifier in Python provides a mechanism to control the exact display of values as strings. It enables the programmer to define the type of data and its presentation style. Python uses the % operator as a placeholder for a format specifier.

1print("Hello, I am %s and I am %d years old." % ('Dino', 32)) 

The above example features two format specifiers, %s and %d which stand for string and decimal integer respectively. The names and age are inserted in place of these specifiers, following the % operator.

Different Types of Format Specifiers

There are various types of format specifiers in Python. Here are a few examples:

  • %s: string
  • %d: decimal integer
  • %f: float
  • %.nf: float rounded off to ’n’ decimal places
  • %x: hexadecimal
  • %o: octal
1print("Decimal: %d \nString: %s \nFloat: %f \nHex: %x \nOct: %o" % (15, 'Hello', 9.6, 255, 15))

Precision in Format Specifier

Format specifier allows controlling the precision of floating point numbers. The precision is the number of digits after the decimal point.

You can use %.nf, where n is the desired number of decimal places.

1print("Pi value with 2 decimal places: %.2f" %(3.14159)) 

The above code prints the value of pi up to two decimal places.

Note

Format specifier inserts the values inside the string dynamically. However, Python introduces f-strings in Python 3.6, which are the preferred way to format strings because of its simplicity and power.

Using Format Specifier with Dictionary

You can also use format specifiers with dictionaries. All you need to do is include the index or key in parentheses, preceded by a percent sign.

1name_and_age = {"name":"Anna","age": 27}
2print("Hello, I am %(name)s and I am %(age)d years old." % name_and_age)

The above code fetches the values from the dictionary and inserts them in the specified places in the string.