3 ms·
From a practical standpoint you have a point. To me string interpolation always seems like the ugly hack compared to building the result with language operators
by weinzierl 3y ago
From a practical standpoint you have a point. To me string interpolation always seems like the ugly hack compared to building the result with language operators [1].
In the end interpolation is either dumb and insufficient for most advanced use cases or it is a complex mini language within the real language with tons of corner cases. Doing everything with language facilities looks much more elegant to me.
[1] The various forms of the concatenation operator (+, ., ||, &, :) are most common but not unique. Perl has a sort of scalar string multiplication where `"*" x 80` turns into 80 asterisks.
- int_19h 3y agoBut string interpolation like that is, effectively, a language operator. Which even in the simplest case (no mini language to format values) is exactly as expressive as concat operator. Python just lets you multiply strings, so you can do ("foo" * 80) etc. Which of course has all the same problems as overloading + for string ops. Perl had a better idea there, but that in turn is kinda forced by the design that implicitly converts strings to numbers and vice versa - you really, really don't want to be in a situation where 1+2, "1"+2, 1+"2", and "1"+"2" are all valid but inconsistent (looking at you, JS...).
- lolinder 3y agoI think you're confusing string interpolation with C-style format strings. Format strings are what you describe: either too weak or a completely insane sub-language. The kind of string interpolation that OP is talking about is different in that what is in between the braces is just an expression and can usually be an arbitrary expression. It doesn't need to be a complex mini language because it just uses the same expression language that you're using everywhere else, with the only additional rule being that your expression must return a string (or in some languages something that can be coerced to a string). From reading this PEP, it sounds like Python's original implementation was a bizarre half measure—it was almost like proper string interpolation but had a bunch of restrictions that showed that they stopped short of changing the parser to just go into expression mode in between the braces.