1

I have a string that I'd like to format but the values I'm using to format may or may not be proper values (None, or ''). In any event that one of these improper values is passed, I still want the string to format, but ignoring any values that will not work. For example:

mystring = "{:02d}:{:02d}"
mystring.format('', 1)

In this case I'd like my output to be :01, thus negating the fact that '' won't work for the first value in the string. I looked at something like

class Default(dict):
    def __missing__(self, key): 
        return key.join("{}")

d = Default({"foo": "name"})

print("My {foo} is {bar}".format_map(d)) # "My name is {bar}"

But as I'm not using a dictionary for values, I don't think this solution will work for me.

2 Answers 2

3

You could write your own formatter and override format_field() to catch these errors and just returns empty strings. Here's the basics (you might want to edit to only catch certain errors):

import string

class myFormat(string.Formatter):
    def format_field(self, value, format_spec):
        try:
            return super().format_field(value, format_spec)
        except ValueError:
            return ''

fmt = myFormat()
mystring = "{:02d}:{:02d}"

print(fmt.format(mystring, *(2, 1)))
# 02:01

print(fmt.format(mystring, *('', 1)))
# :01
Sign up to request clarification or add additional context in comments.

4 Comments

Is there any way to incorporate a value other than '' in the return statement? An optional parameter, for example. If I wanted to return missing:01, for example, instead of a blank string?
@AGH_TORN if you return 'missing' in the except block you will get missing:01. If that not working for you?
I thought it would but it is not working. I added an optional parameter in the format_field function that is returned in the return statement, however, it seems like it's just skipping over it. I still get :01 returned.
I should specify, I added the optional parameter to the function and the return statement is returning that parameter. That's the portion that's not working.
0

You could use a try-except to check if each value is valid:

out = []
for v in ['', 1]:
    # Check if v can be converted to a decimal number
    try:
        out.append(format(v, '02d'))
    except (ValueError, TypeError):
        out.append('')

print(':'.join(out))  # -> :01

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.