ProfHase85
ProfHase85

Reputation: 12193

Python - convert to string with formatter as parameter

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

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?

Upvotes: 2

Views: 138

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123420

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 %.

Upvotes: 2

Related Questions