Home / Definitions / String Interpolation

String Interpolation

Kirsty Moreland
Last Updated February 2, 2024 2:50 am

In computer programming, string interpolation is the process of replacing placeholders with values in a string literal. A string is a sequence of characters. A string literal is a sequence of characters from the source character set enclosed in quotation marks. They are used to represent a sequence of characters that form a null-terminated string. String interpolation is a form of simple template processing and allows for easier and more intuitive string formatting and content-specification.

For example, if a template is made to say hello to a person, such as “hello {first name}”, the goal would be to replace the placeholder for the first name with a name of an actual person. String interpolation works to complete this task.

Placeholders are typically represented by a bare or a sigil, such as $ or %. String interpolation is common in programming languages that use string representations of data, such as Python, Scala, and Ruby. String interpolation is beneficial for code clarity, reducing memory use, and increasing speed.

String interpolation examples

Examples of string interpolation within different programming languages can be found below.

Python

Program to run in Python:

name = 'World'
program = 'Python'
print(f'Hello {name}! This is {program}')

Output of the program:

Hello World! This is Python

JavaScript

Program to run in JavaScript:

var apples = 4;
var bananas = 3;
console.log(`I have ${apples} apples`);
console.log(`I have ${apples + bananas} fruit`);

Output of the program:

I have 4 apples                                                         
I have 7 fruit

C#

Program to run in C#:

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

Output of the program:

I have 4 apples                                                     
I have 7 fruit

PHP

Program to run in PHP:

<?php
$apples = 5;
$bananas = 3;
echo "There are $apples apples and $bananas bananas.";
echo "n";
echo "I have ${apples} apples and ${bananas} bananas.";

Output of the program:

There are 5 apples and 3 bananas.                                          
I have 5 apples and 3 bananas.