Notes

String interpolation in different programming languages

Edit on GitHub

Programming
2 minutes

Here are some interpolation examples for comparison

Bash

1#!/bin/bash
2string = "${someone} was looking for ${something} in the general vicinity of ${somewhere}"

C# ($ - string interpolation)

1// csharp
2
3// Composite formatting:
4string = "Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date;
5
6// String interpolation:
7string = $"{someone} was looking for {something} in the general vicinity of {somewhere}"

You can use conditional operators inside the interpolated expression

1Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old."); // Sami is 29 years old.

JavaScript (Template literals)

1// javascript
2string = `${someone} was looking for ${something} in the general vicinity of ${somewhere}`

Python (template strings)

1# python
2# %s is used for strings whereas %d is used for numbers.
3string = "%s was looking for %s in the general vicinity of %s" % (someone, something, somewhere)
4
5# python 3.6
6string = f"{someone} was looking for {something} in the general vicinity of {somewhere}"

Ruby

1# ruby
2string = "#{someone} was looking for #{something} in the general vicinity of #{somewhere}"

PHP

PHP has a HEREDOC syntax

 1function echo_card($title = "Default Title", $desc = "Default Description", $img = "/images/fallback.jpg") {
 2   $html = <<<"EOT"
 3      <div class="card">
 4         <img src="$img" alt="">
 5         <h2>$title</h2>
 6         <p>$desc</p>
 7      </div>
 8EOT;
 9
10   echo $html;
11}
1echo_card($title, $desc, $img);