You can't do it within the format string itself, but using named placeholders, you can pass a dict-like thing to .format_map that contains a generic default value, or combine a dict of defaults for each value with the provided dict to override individually.

Examples:

  1. With a defaulting dict-like thing:

    from collections import Counter
    
    fmt_str = "I have {spam} cans of spam and {eggs} eggs."
    
    print(fmt_str.format_map(Counter(eggs=2)))
    

    outputs I have 0 cans of spam and 2 eggs.

  2. With combining dict of defaults:

    def format_groceries(**kwargs):
        defaults = {"spam": 0, "eggs": 0, **kwargs}  # Defaults are replaced if kwargs includes same key
        return "I have {spam} cans of spam and {eggs} eggs.".format(defaults)
    
    print(format_groceries(eggs=2))
    

    which behaves the same way.

With numbered placeholders, the solutions end up uglier and less intuitive, e.g.:

def format_up_to_two_things(*args)
    if len(args) < 2:
        args = ('default text', *args)
    return "Text {0} here, and text {1} there".format(*args)

The tutorial doesn't really go into this because 99% of the time, modern Python is using f-strings, and actual f-strings generally don't need to deal with this case, since they're working with arbitrary expressions that either work or don't work, there's no concept of passing an incomplete set of placeholders to them.

Answer from ShadowRanger on Stack Overflow
Top answer
1 of 3
1

You can't do it within the format string itself, but using named placeholders, you can pass a dict-like thing to .format_map that contains a generic default value, or combine a dict of defaults for each value with the provided dict to override individually.

Examples:

  1. With a defaulting dict-like thing:

    from collections import Counter
    
    fmt_str = "I have {spam} cans of spam and {eggs} eggs."
    
    print(fmt_str.format_map(Counter(eggs=2)))
    

    outputs I have 0 cans of spam and 2 eggs.

  2. With combining dict of defaults:

    def format_groceries(**kwargs):
        defaults = {"spam": 0, "eggs": 0, **kwargs}  # Defaults are replaced if kwargs includes same key
        return "I have {spam} cans of spam and {eggs} eggs.".format(defaults)
    
    print(format_groceries(eggs=2))
    

    which behaves the same way.

With numbered placeholders, the solutions end up uglier and less intuitive, e.g.:

def format_up_to_two_things(*args)
    if len(args) < 2:
        args = ('default text', *args)
    return "Text {0} here, and text {1} there".format(*args)

The tutorial doesn't really go into this because 99% of the time, modern Python is using f-strings, and actual f-strings generally don't need to deal with this case, since they're working with arbitrary expressions that either work or don't work, there's no concept of passing an incomplete set of placeholders to them.

2 of 3
1

If you only needed to insert an exact number of values positionally

as a lambda

meh = lambda x='default x',y='default y': 'Text {0} here, Text {1} here'.format(x,y)
print(meh(3,7))

as a function

def meh(x='default x',y='default y'):
  return "Text {0} here, Text {1}".format(x,y)
print(meh(3,7))
🌐
Stack Overflow
stackoverflow.com › q › 22626441
python - Default values for string format use in string (template) - Stack Overflow
(lets say default values for those 3 paramters should be 'is running') ... Save this answer. ... Show activity on this post. ... def test(isServerRunning='is running', isNTPrunning='is running', isAppRunning='is running'): return template.format( isServerRunning=isServerRunning, isNTPrunning=isNTPrunning, isAppRunning=isAppRunning)
🌐
Python
docs.python.org › 3 › library › string.html
Common string operations — Python 3.14.7 documentation
Returns a tuple (obj, used_key). The default version takes strings of the form defined in PEP 3101, such as “0[name]” or “label.title”. args and kwargs are as passed in to vformat().
🌐
PyFormat
pyformat.info
PyFormat: Using % and .format() for great good!
Python has had awesome string formatters for many years but the documentation on them is far too theoretic and technical. With this site we try to show you the most common use-cases covered by the old and new style string formatting API with practical examples.
🌐
Guru99
guru99.com › home › python › python string format() explain with examples
Python String format() Explain with EXAMPLES
July 10, 2026 - No. Python strings are immutable, so format() builds and returns a brand-new string while leaving the template unchanged. Assign the result to a variable, for example message = template.format(value), to keep the formatted text for later use.
🌐
Telerik
telerik.com › blogs › string-formatting-python
String Formatting in Python
January 6, 2023 - On top of string interpolation, we can format values within the string literals using Python’s format specification mini-language. Let’s look at that next. We can optionally specify type conversion and format_spec options in a formatted string or a string with the format() method. ... An exclamation mark denotes a conversion and a colon denotes a format_spec option. ... Type conversion is done before formatting the string. !s applies the str(value) method to a value, while !r applies the repr(value) method. For example, if we wanted to format a string in quotes, we would use the !r modifier.
Find elsewhere
🌐
Real Python
realpython.com › python-formatted-output
A Guide to Modern Python String Formatting Tools – Real Python
February 1, 2025 - Up to this point, you’ve coded examples that show how to use the f_expression component in f-strings and the field_name component in .format(). In the following sections, you’ll learn about the other two components, which work similarly in f-strings and .format(). ... The conversion component defines the function to use when converting the input value into a string. Python can do this conversion using built-in functions like the following: str() provides a user-friendly string representation. repr() provides a developer-friendly string representation. By default, both f-strings and the .format() method use str().
🌐
Python
peps.python.org › pep-3101
PEP 3101 – Advanced String Formatting | peps.python.org
Within a format string, each positional argument is identified with a number, starting from zero, so in the above example, ‘a’ is argument 0 and ‘b’ is argument 1. Each keyword argument is identified by its keyword name, so in the above example, ‘c’ is used to refer to the third argument. There is also a global built-in function, ‘format’ which formats a single value:
🌐
W3Schools
w3schools.com › python › ref_string_format.asp
Python String format() Method
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... The format() method formats the specified value(s) and insert them inside the string's placeholder.
🌐
Python Course
python-course.eu › python-tutorial › formatted-output.php
22. Formatted Output | Python Tutorial | python-course.eu
The string class contains further ... S centred in a string of length width. Padding is done using the specified fill character. The default value is a space....
🌐
w3resource
w3resource.com › python › python-format.php
Python String Formatting
April 14, 2026 - 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.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-string-formatters-in-python-3
How To Use String Formatters in Python 3 | DigitalOcean
This tutorial will guide you through some of the common uses of string formatters in Python, which can help make your code and program more readable and user…
Top answer
1 of 3
44

The recommendation in PEP 3101 is to subclass Formatter:

import string
class PartialFormatter(string.Formatter):
    def __init__(self, missing='~~', bad_fmt='!!'):
        self.missing, self.bad_fmt=missing, bad_fmt

    def get_field(self, field_name, args, kwargs):
        # Handle a key not found
        try:
            val=super(PartialFormatter, self).get_field(field_name, args, kwargs)
            # Python 3, 'super().get_field(field_name, args, kwargs)' works
        except (KeyError, AttributeError):
            val=None,field_name 
        return val 

    def format_field(self, value, spec):
        # handle an invalid format
        if value==None: return self.missing
        try:
            return super(PartialFormatter, self).format_field(value, spec)
        except ValueError:
            if self.bad_fmt is not None: return self.bad_fmt   
            else: raise

fmt=PartialFormatter()
data = {'n': 3, 'k': 3.141594, 'p': {'a': '7', 'b': 8}}
print(fmt.format('{n}, {k:.2f}, {p[a]}, {p[b]}', **data))
# 3, 3.14, 7, 8
del data['k']
data['p']['b'] = None
print(fmt.format('{n}, {k:.2f}, {p[a]:.2f}, {p[b]}', **data))
# 3, ~~, !!, ~~

As set up, it will print ~~ if a field or attribute is not found and !! if an invalid format is used given the field value. (Just use None for the keyword argument bad_fmt if you want the default of a value error raised.)

To handle missing keys, you need to subclass both get_field to catch the KeyError or AttributeError and format_field to return a default value for the missing key.

Since you are catching format_field errors, you can catch a bad format field as well by catching the ValueError from the superclass.

2 of 3
11

If you're able to do the formatting separately you could use Template.safe_substitute which gracefully handles missing values:

>>> from string import Template
>>> t = Template("$a $b $c")
>>> t.safe_substitute(a=3)
'3 $b $c'
🌐
GeeksforGeeks
geeksforgeeks.org › python-string-format-method
Python String format() Method - GeeksforGeeks
March 26, 2025 - String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string.You will learn different methods of string formatting with examples for better understanding. Let's look at them now!How to Format Strings in Pyt · 9 min read What does %s mean in a Python format string?
🌐
Programiz
programiz.com › python-programming › methods › string › format
Python String format()
# default arguments print("Hello {}, your balance is {}.".format("Adam", 230.2346)) # positional arguments print("Hello {0}, your balance is {1}.".format("Adam", 230.2346)) # keyword arguments print("Hello {name}, your balance is {blc}.".format(name="Adam", blc=230.2346)) # mixed arguments ...