by methodover · 11y ago · 0 comments
cache.add_message("Hey, your {zoop} is {boop}".format(zoop=zoop, boop=boop))
That that call to "format" just kind of sucks -- it repeats what's already pretty obvious by looking at the string. It's specially crappy when you have strings that need lots of variables. We've taken to doing this recently, which I'm usually okay with: cache.add_message("Hey, your {} is {}".format(zoop, boop))
The downside of that is you have to make sure that the order of the arguments matches exactly with the order of the empty brackets. It's kinda error prone... But generally not that big of a deal.We could also do this...
cache.add_message("Hey, your %s is %s" % zoop, boop))
Or this... cache.add_message("{1} alert! Hey, your {0} is {1}".format(zoop, boop))
So yeah, I would argue that string formatting in Python is ALREADY in a kinda nasty place. There's ALREADY a bunch of ways to do it, and it all just kinda sucks.IMO, Ruby-style string formatting is probably the nicest I've seen. If it were in Python, it absolutely would be THE way to do string formatting, I bet.
cache.add_message("Hey, your {zoop} is {boop}")
So much nicer. bar='batz'
"foo #{bar} #{0.5+0.5}"
=> "foo batz 1.0"
"foo %s %.2f" % [bar, 1.0]
=> "foo batz 1.00"