As PEP 3101, string.format(**other_dict) is not available.

If the index or keyword refers to an item that does not exist, then an IndexError/KeyError should be raised.

A hint for solving the problem is in Customizing Formatters, PEP 3101. That uses string.Formatter.

I improve the example in PEP 3101:

from string import Formatter

class UnseenFormatter(Formatter):
    def get_value(self, key, args, kwds):
        if isinstance(key, str):
            try:
                return kwds[key]
            except KeyError:
                return key
        else:
            return Formatter.get_value(key, args, kwds)

string = "{number_of_sheep} sheep {has} run away"
other_dict = {'number_of_sheep' : 1}

fmt = UnseenFormatter()
print fmt.format(string, **other_dict)

The output is

1 sheep has run away
Answer from emesday 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))
Discussions

string formatting - How to get Python to gracefully format None and non-existing fields - Stack Overflow
Instead of an error message, how can I get Python to more gracefully format the None's and non existent fields? To give an example, I would like to see in the output something more like: ... Ideally, of course, I would like to be able to specify the string used instead of those missing values. More on stackoverflow.com
🌐 stackoverflow.com
python - string.format() with optional placeholders - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
python - String format with optional dict key-value - Stack Overflow
Is there any way to format string with dict but optionally without key errors? This works fine: opening_line = '%(greetings)s %(name)s !!!' opening_line % {'greetings': 'hello', 'name': 'john'} ... More on stackoverflow.com
🌐 stackoverflow.com
Python default parameter with format() - Stack Overflow
a.format does not change the original string a, strings are immutable so all a.format does is create a new string. Any time you modify a string it creates a new object. Unless you are using concatenation then to change the value of a you need to reassign a to the new object. More on stackoverflow.com
🌐 stackoverflow.com
April 22, 2015
🌐
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().
🌐
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
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:
🌐
PyFormat
pyformat.info
PyFormat: Using % and .format() for great good!
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. All examples on this page work out of the box with with Python 2.7, 3.2, 3.3, 3.4, and 3.5 without requiring any additional libraries.
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("b $c")
>>> t.safe_substitute(a=3)
'3 c'
Find elsewhere
🌐
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.
🌐
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
docs.python.org › 3.4 › library › string.html
6.1. string — Common string operations — Python 3.4.10 documentation
... Given field_name as returned by parse() (see above), convert it to an object to be formatted. 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().
🌐
Python.org
discuss.python.org › ideas
F-string by default? - Ideas - Discussions on Python.org
December 31, 2022 - Have we considered a from __future__... import to have all strings in the file work as f-strings without needing the f-prefix? Example: from __future__ import f_string_by_default a = 'hello' print('{a} world') ^ pri…
🌐
Telerik
telerik.com › blogs › string-formatting-python
String Formatting in Python
January 6, 2023 - 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. In the code below, we have defined the __str__() method.
🌐
Reddit
reddit.com › r/learnpython › default value for string parameter, empty string or none?
r/learnpython on Reddit: Default value for string parameter, empty string or None?
February 19, 2022 -

Consider the following class:

class Team:
    def __init__(self, team_members, the_captain):
        ...

Here team_members is a list of strings and the_captain is a string. Now if the_captain is not passed to the constructor, team captain will be selected randomly from team members, otherwise team captain will be the_captain.

I want to set a default value for the_captain, What do you recommend for the default value, None or empty string? In other words which of the following constructor definitions do you think is better?

1

class Team:
    def __init__(self, team_members, the_captain=None):
        ...

2

class Team:
    def __init__(self, team_members, the_captain=""):
        ...

Thanks

🌐
Python documentation
docs.python.org › 3 › tutorial › inputoutput.html
7. Input and Output — Python 3.14.7 documentation
Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are several ways to format output. To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark.
🌐
GeeksforGeeks
geeksforgeeks.org › python-string-format-method
Python String format() Method - GeeksforGeeks
March 26, 2025 - In Python, the %s format specifier is used to represent a placeholder for a string in a string formatting operation. It allows us to insert values dynamically into a string, making our code more flexible and readable.
🌐
Guru99
guru99.com › home › python › python string format() explain with examples
Python String format() Explain with EXAMPLES
July 10, 2026 - The value that we want to be replaced is a string. ... Using String Formatting in Python, we want the curly brackets ({}) to be replaced with a string value. The value is given to format(“Guru99”).