String interpolation is a method used in programming to incorporate variable values or expressions within a string. It enables the creation of dynamic strings, where parts of the string’s content can change based on variables or expressions evaluated at runtime.
In string interpolation, placeholders within a string are replaced by the values of variables. For example, you might have a template string with placeholders indicating where to insert values, and the actual output string will replace those placeholders with variable values.
Bash
In Bash scripting, string interpolation is often done using double quotes to allow variable expansions:
username="Rabi"
echo "Hello, $username!"
This script declares a variable username
and then uses it within a string. The $username
within the double quotes is replaced by the actual value of username.
JavaScript
JavaScript uses template literals (strings enclosed by backticks ) for interpolation, which is more straightforward than the older method of string concatenation:
let username = 'Rabi';
console.log(`Hello, ${username}!`);
Python
Python uses formatted string literals, or f-strings
, introduced in Python 3.6:
username = "Rabi"
print(f"Hello, {username}!")