2

I am trying to write a function which takes two arguments:

  • an object
  • a formatter string (as specified in docs)

which then returns a formatted string: What I tried is sort of:

def my_formatter(x, form):
    return str(x).format(form)

What I am expecting is:

s = my_formatter(5, "%2f")
# s = 05
t = my_formatter(5, "%.2")
# t = 5.00

etc...

The format function unfortunately does not work like that. Any ideas?

1 Answer 1

2

For that style of formatting you'd have to use the string % values string formatting operation:

def my_formatter(x, form):
    return form % x

You'd also have to alter your format; to get 05 you'd have to use "%02d", not "%2f".

You were getting confused by the str.format() method, which uses a different formatting syntax, and you got the arguments swapped; you'd use form.format(x) instead.

You probably want to look into the built-in format() function here; the syntax is slightly different, but offers more features:

>>> format(5, '02d')
'05'
>>> format(5, '.2f')
'5.00'

That's pretty close to what you were already using, minus the %.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, exactly, I was confused by the str.format method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.