Cara menggunakan python format specifier

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Formatting Python Strings

In the previous tutorial in this introductory series, you got a first look at how you can format your strings with Python f-strings. You’ll learn more about this technique towards the end of this tutorial.

Since f-strings are comparably new to the Python language, it’s good for you to be familiar with a second, slightly older technique as well. You’re likely to encounter it in older Python code.

In this tutorial, you’ll learn about:

  1. The string .format() method
  2. The formatted string literal, or f-string

You’ll learn about these formatting techniques in detail and add them to your Python string formatting toolkit.

You might notice that there are a lot of different ways to format strings in Python, which breaks with one of Python’s very own mantras:

There should be one– and preferably only one –obvious way to do it. —Tim Peters, The Zen of Python

The different string formatting techniques have developed historically over the years that Python has existed and grown. Older techniques are kept around to ensure backward compatibility, and some even have specific use cases.

If you’re getting started with Python and you’re looking for a single way to format your strings, then stick with Python 3’s f-Strings. If you’ve encountered strange-looking string format code and want to know more, or you need to work with older versions of Python, then it’s a good idea to learn about the other techniques as well.

The Python String .format() Method

The Python string .format() method was introduced in version 2.6. It’s similar in many ways to the string modulo operator, but .format() goes well beyond in versatility. The general form of a Python .format() call is shown below:

<template>.format(<positional_argument(s)>, <keyword_argument(s)>)

Note that this is a method, not an operator. You call the method on