Search code examples
string-formattingstring-interpolation

String formatting vs String Interpolation


Please help me understand the difference between the two concepts of String Formatting and String Interpolation.

From Stackoverflow tag info for string-interpolation:

String interpolation is the replacement of defined character sequences in a string by given values. This representation may be considered more intuitive for formatting and defining content than the composition of multiple strings and values using concatenation operators. String interpolation is typically implemented as a language feature in many programming languages including PHP, Haxe, Perl, Ruby, Python, C# (as of 6.0) and others.

From Stackoverflow tag info for string-formatting:

Commonly refers to a number of methods to display an arbitrary number of varied data types into a string.

To me, they appear to be similar, but I hope there's some difference.

Also, kindly clarify whether these are some technology-specific concepts, or, technology-agnostic concepts. (I was reading about these concepts in the context of Python. But quick google and bing searches brought up related articles in other programming languages such as Java, C#, etc.)


Solution

  • String formatting is a rather general term of generating string content from data using some parameters. For example, creating date strings from date objects for a specific date format, number strings from numbers with a particular number of decimal digits or a number of leading spaces and zeroes etc. It can also involve templates, like in sprintf function present in C or many other languages, or e.g. str.format in Python. For example, in Ruby:

    sprintf("%06.2f", 1.2) # float, length 6, 2 decimals, leading zeroes if needed
    # => "001.20"
    

    String interpolation is a much more restricted concept: evaluating expressions embedded inside string literals and replacing them with the result of such evaluation. For example, in Ruby:

    "Two plus two is #{2+2}"
    # => "Two plus two is 4"
    

    Some languages can perform formatting inside interpolation. For example, in Python:

    f"Six divided by five is {6/5:06.2f}"
    # => "Six divided by five is 001.20"
    

    The concepts are language-agnostic. However, it is not guaranteed that all programming languages will have a built-in capability for one or both of them. For example, C has no string interpolation, but it has string formatting, using the printf family of functions; and until somewhat recently, JavaScript did not have either, and any formatting was done in a low-tech way, using concatenation and substringing.