Is there a way to have a default value when doing a string formatting? For example:
s = "Text {0} here, and text {1} there"
s.format('foo', 'bar')
What I'm looking for is setting a default value for a numbered index, so that it can be skipped in placeholder, e.g. something like this:
s = "Text {0:'default text'} here, and text {1} there"
I checked https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings and didn't find what I need, may be looking in a wrong place?
Thanks.
CodePudding user response:
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:
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.
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.
CodePudding user response:
So let's assume you want to set a default value and only exceptional values for certain conditions.
a = 2
b = 2
text = "this is the default value {0} and this is second value: {1}".format(a if a==b else None,b)
print(text)
if conditions met it prints a, otherwise None. So instead of None you can write whatever you want to be default.