format - Python - convert to string with formatter as parameter -


i trying write function takes 2 arguments:

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

which returns formatted string: tried sort of:

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

what expecting is:

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

etc...

the format function unfortunately not work that. ideas?

for style of formatting you'd have use string % values string formatting operation:

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

you'd have alter format; 05 you'd have use "%02d", not "%2f".

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

you want built-in format() function here; syntax different, offers more features:

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

that's pretty close using, minus %.


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -