3 ms·
Well... String formatting already sorta breaks the "only one obvious way to do something" rule. I dunno about you, but we have string formatting all over the pl
by methodover 11y ago
Well... String formatting already sorta breaks the "only one obvious way to do something" rule. I dunno about you, but we have string formatting all over the place in our code. I would wager that every single module in our codebase has something that looks like this:
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.
- dragonwriter 11y agoActually, I kind of like the existing Python ways better in many respects from the Ruby one, since it lets you separate format strings from the parameters passed to them, and reuse format strings more easily (which is especially useful if you want to move string literals out of code and into resources, because then you can include format strings in that as well.)
- methodover 11y agoOh hey, I didn't even think of that. That's a really good point.
- stouset 11y agoYou can do this in Ruby too, with sprintf. It's almost as if there are multiple, complimentary ways of accomplishing similar tasks, depending on your needs.
- moe 11y agoYou don't even need sprintf, Ruby supports Python-style interpolation, too: bar='batz' "foo #{bar} #{0.5+0.5}" => "foo batz 1.0" "foo %s %.2f" % [bar, 1.0] => "foo batz 1.00"
- stouset 11y ago% is an alias for sprintf. :)
- dragonwriter 11y agoYeah, I was comparing the Python and Ruby features already under discussion in the thread, not what is available in each language, but that's useful to point out given that people might not be aware of it.