Skip to main content

String.format()

·399 words·2 mins
Posts python
Table of Contents
Although string.format() is generally slower than f-strings, it has a few unique capabilities that cannot be replicated, primarily due to its dynamic nature.

We use f-string and string.format() for string formatting. And both have differ in syntax, readability, performance and capabilities.

f-stringstring.format()
SyntaxUse a concise syntax with an f prefixUse placeholders {} in the string with arguments to the format()
ReadabilityMore readable and intuitiveLess concise esp with multiple arguments
PerformanceGenerally faster (evaluated at compile time)Slower (involes method calls and runtime processing
FlexibilityDirectly embed expressionsSupports positional, keyword, and indexed placeholders (more control)
DebuggingHandle error at runtimeMore forgiving with missing arguments or handled dynamically

Why String.format()?
#

Here are the a few capabilities that only work in string.format().

  1. Dynamic Placeholder Reuse:

    template = "{0} loves {1} and {0} also loves {2}"
    result = template.format("Alice", "Bob", "Charlie")
    # Output: Alice loves Bob and Alice also loves Charlie
    
  2. Dynamic Template Construction:

    • Support storing the template as a string and apply format() later with varying arguments.
    template = "Hello, {name}!"  # Could come from a file or user input
    result = template.format(name="Alice")
    
  3. Advanced Mapping with Dictionaries:

    • Support unpacking dictionaries directly into placeholders using **kwargs.
    data = {"name": "Alice", "age": 30}
    result = "Name: {name}, Age: {age}".format(**data)
    # Output: Name: Alice, Age: 30
    
  4. Legacy Compatibility:

    • string.format() is available in Python 2.x and earlier versions of Python 3.
  5. Custom Formatting with Custom Specification:

    • string.format() can be used with custom formatters by overridding the __format__ method.
    class Person:
    def __init__(self, name):
        self.name = name
    def __format__(self, format_spec):
        return f"Person: {self.name.upper()}" \
               if format_spec == "upper" else self.name
    
    person = Person("Alice")
    result = "Hello, {0:upper}!".format(person)
    # Output: Hello, Person: ALICE!
    

Conclusion
#

Generally, f-string is preferred for its simplicity and speed. And string.format() can offers unique features like placeholder reuse, dynamic template hanlding, and dictionary unpacking that f-string can’t directly replicate.

For most modern Python applications, f-string is the go-to choice, but string.format() remains relevant for specific use cases that involving legacy code.

Use f-string when:

  • Working in Python 3.6+ and prioritize readability and performance.
  • The string formatting is straightforward with variables or simple expressions.
  • The template is static and defined inline.

Use string-format() when:

  • Need to reuse placeholders or work with dynamic templates.
  • Dealing with dictionary unpacking or complex argument mapping.
  • Need compatibility with Python versions before 3.6.
  • Need to implement custom formatting logic via __format__.

Related

Adding Python3.11
·261 words·2 mins
Posts 101 python ubuntu
Steps to install alternate Python version for Noble
Mistake in List Iteration
·169 words·1 min
Posts 101 python
Unexpected behaviour in your Python loops.
Understanding AsyncIO by Code
·691 words·4 mins
Posts 101 code async python
Let’s learn AsyncIO by code.