What is string interpolation

In computer programming, string interpolation or variable interpolation is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

String interpolation is common in many programming languages which make heavy use of string representations of data, such as C, Perl, PHP, Python, Ruby, Groovy, Scala and Swift, and most Unix shells.

Two modes of literal expression are usually offered: one with interpolation enabled, the other without ("raw string"). Placeholders are usually represented by a bare or a named sigil, (typically $ or %), e.g. $placeholder or %123. Expansion of the string usually occurs at run time.

Samples

C# .NET

var apples = 4;
// Before C# 6.0
System.Console.WriteLine(String.Format("I have {0} apples", apples));
// C# 6.0
System.Console.WriteLine($"I have {apples} apples");

The output will be:

I have 4 apples

Swift

In Swift you can create a new String value from a combination of constants, variables, literals, and expressions by including their values inside a string literal. Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash(\).

let apples = 4
print("I have \(apples) apples")

The output will be:

I have 4 apples

Ruby

apples = 4
puts "I have  apples"
# or
puts "I have %s apples" % apples
# or
puts "I have %{a} apples" % {a: apples}

The output will be:

I have 4 apples

Python

# in Python 2
apples = 4
print "I have %d apples" % apples
print "I have %(apples)d apples" % locals()
# or in Python 2.6
print "I have {} apples".format(apples)
print "I have {a} apples".format(a=apples)
# or in Python 3
print("I have {apples} apples".format(**locals()))
print("I have",apples,"apples",sep=" ")
# or with Python 3.6
print(f"I have {apples} apples")

References & Resources

  • N/A