Taskintro
Interpolate values into a string
Also called string interpolation, interpolate variables, f-string, template literal, interpolated string, $"...", format!, expressions in strings, escape braces, embed values in text, Mary had a little lamb.
Build a sentence from values with string interpolation: a name, a count with the right plural and a computed total. Escape the literal braces, and never treat a value as a format.
- Evidence
- Code in 10 languages
Task
Build a string from values. The Rosetta Code task says: "Given a string and defined variables or values, string interpolation is the replacement of defined character sequences in the string by values or variable values"1. Its example puts the word little into the sentence Mary had a little lamb. This task adds three more parts: a number, an expression and literal braces.
The function describe_order(name, count, price) returns the sentence:
Order {NAME}: COUNT items, total TOTAL
NAMEis the name, inside literal braces.COUNTis the count, and the word isitemif the count is 1 anditemsotherwise.TOTALiscount * price, rounded to 2 decimals.
For example, describe_order("Ada", 3, 1.5) is "Order {Ada}: 3 items, total 4.50", and describe_order("Bob", 1, 0.5) is "Order {Bob}: 1 item, total 0.50".
The name is a value, not a part of the template. If the name is {x}, 50% off or ${HOME}, the result has those characters as they are.
Solutions
Six tier 1 languages have interpolation in the language. Java, Go and C have none, so their solutions use a format function.
| Language | Mechanism | Literal brace |
|---|---|---|
| Python | f-string f"...{name}..." |
{{ and }} |
| JavaScript, TypeScript | template literal `...${name}...` |
{ and } as they are |
| Java | String.format |
{ and } as they are |
| C# | interpolated string $"...{name}..." |
{{ and }} |
| Go | fmt.Sprintf |
{ and } as they are |
| Rust | format!("...{name}...") |
{{ and }} |
| C | snprintf |
{ and } as they are |
| C++ | std::format |
{{ and }} |
| Bash | double quotes "...${name}..." |
{ and } as they are |
- Python. An f-string. "F-strings provide a way to embed expressions inside string literals, using a minimal syntax"2. A placeholder can hold an expression, such as
count * price, with a format after a colon. For a brace, "any doubled braces '{{' or '}}' inside literal portions of an f-string are replaced by the corresponding single brace"2, so{{{name}}}is a brace, the name and a brace. - JavaScript. A template literal, in backticks. Template literals are used "for string interpolation (to create strings by doing substitution of placeholders)"3. A single brace needs no escape, because a placeholder starts with
${. - TypeScript. The same code as JavaScript, with types.
- Java. Java has no interpolation in the language, so the solution uses
String.formatwithLocale.ROOT. - C#. An interpolated string. "To include a brace"4 in the result, use two braces. "To use a conditional operator in an interpolation expression, enclose that expression in parentheses"4, because a colon starts the format.
string.Create(CultureInfo.InvariantCulture, $"...")formats the number with a dot. - Go.
fmt.Sprintf. Go has no interpolation, and the package fmt "implements formatted I/O with functions analogous to C's printf and scanf"5. - Rust.
format!takes variables by name: "If a named parameter does not appear in the argument list, format! will reference a variable with that name in the current scope"6. A name in braces must be a variable, not an expression, so the solution computes the total and the plural ending first. "the { character is escaped with {{"6. - C.
snprintfinto a buffer. The solution returns the length of the full text. - C++.
std::format, with the brace syntax of Rust and Python. It has no names, so the values come after the format string. - Bash. Double quotes expand
$nameand${name}. "Enclosing characters in double quotes"7 keeps each character, except$, a backquote, a backslash and sometimes!. Bash has no float arithmetic, so the solution usesawkfor the total.
The Python solution, with all three parts in one f-string:
def describe_order(name, count, price):
return f"Order {{{name}}}: {count} item{'' if count == 1 else 's'}, total {count * price:.2f}"
print(describe_order("Ada", 3, 1.5))
print(describe_order("Bob", 1, 0.5))
print(describe_order("{x}", 2, 1.25))
Order {Ada}: 3 items, total 4.50
Order {Bob}: 1 item, total 0.50
Order {{x}}: 2 items, total 2.50
The Rust solution computes the expressions first, because a name in braces must be a variable:
fn describe_order(name: &str, count: i64, price: f64) -> String {
let ending = if count == 1 { "" } else { "s" };
let total = count as f64 * price;
format!("Order {{{name}}}: {count} item{ending}, total {total:.2}")
}
fn main() {
println!("{}", describe_order("Ada", 3, 1.5));
println!("{}", describe_order("50% off", 4, 2.5));
}
Order {Ada}: 3 items, total 4.50
Order {50% off}: 4 items, total 10.00
Edge cases
- Zero items. The word is
items:Order {Ada}: 0 items, total 0.00. - One item. The word is
item. The test for the plural iscount == 1, notcount > 1, because 0 also takes the plural in English. - Empty name. The result has two braces with nothing between them:
Order {}: 2 items, total 2.00. - Braces, percent signs and dollar signs in the name.
{x}givesOrder {{x}}: ...,50% offgivesOrder {50% off}: ..., and${HOME}givesOrder {${HOME}}: .... The value is never read as a template. - Rounding of the total.
3 * 19.99is a little less than 59.97 as a binary float, and it rounds to59.97. - Large totals.
1000 * 1234.56gives1234560.00, with no exponent and no group separators. - Negative price. A refund of
-4.5for 2 items givestotal -9.00.
Pitfalls
- A value used as a template. Interpolation reads the template at compile time, so a value with braces is safe. But code that builds a format string from a value is not safe. In Python,
("Order " + name).format()fails for the name{x}, becauseformatreads the braces of the value as a placeholder:
This code runs but gives a wrong answer on purpose.
name = "{x}"
try:
print(("Order " + name + ": done").format())
except KeyError as e:
print("KeyError", e)
print(f"Order {name}: done")
KeyError 'x'
Order {x}: done
The same mistake in C, printf(name), is a security weakness. Pass the value as an argument.
- An f-string without the f.
"Order {name}"without thefis a normal string, so the braces stay in the result. In JavaScript,"${name}"in double quotes is also a normal string. Only backticks make a template literal. - A conditional in C#.
$"{count == 1 ? "" : "s"}"does not compile, because the colon starts a format. Put the expression in parentheses. - Single quotes in Bash.
'$name'in single quotes stays as the text$name. Use double quotes, and quote each expansion so that the shell does not split the value into words. - The locale of the number. In C#, an interpolated string formats a number with the culture of the thread, so a German computer gives
4,50. Usestring.Create(CultureInfo.InvariantCulture, ...)orFormattableString.Invariantfor text that a program reads. See Locale-aware formatting. - Interpolation into code. Do not build SQL, HTML or shell commands with interpolation. A value with a quote changes the command. Use parameters or a library that escapes the values.
Related tasks
- String interpolation: how interpolation works in each language.
- Print formatted output: values in fixed columns.
- Format specifiers: the formats after the colon, such as
.2f. - Locale-aware formatting: numbers with the symbols of a language and region.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
def describe_order(name: str, count: int, price: float) -> str:
"""Return "Order {name}: count item(s), total count*price".
The doubled braces are literal braces. The total has 2 decimals.
"""
return f"Order {{{name}}}: {count} item{'' if count == 1 else 's'}, total {count * price:.2f}"
if __name__ == "__main__":
print(describe_order("Ada", 3, 1.5))
test_order.py 26 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
import pytest
from order import describe_order
CASES = [
("three-items", "Ada", 3, 1.5, "Order {Ada}: 3 items, total 4.50"),
("one-item", "Grace", 1, 19.99, "Order {Grace}: 1 item, total 19.99"),
("many-items", "Linus", 12, 0.25, "Order {Linus}: 12 items, total 3.00"),
("zero-items", "Ada", 0, 9.99, "Order {Ada}: 0 items, total 0.00"),
("one-item-plural", "Bob", 1, 0.5, "Order {Bob}: 1 item, total 0.50"),
("empty-name", "", 2, 1.0, "Order {}: 2 items, total 2.00"),
("braces-in-name", "{x}", 2, 1.25, "Order {{x}}: 2 items, total 2.50"),
("percent-in-name", "50% off", 4, 2.5, "Order {50% off}: 4 items, total 10.00"),
("dollar-in-name", "${HOME}", 1, 3.0, "Order {${HOME}}: 1 item, total 3.00"),
("product-rounds", "Cy", 3, 19.99, "Order {Cy}: 3 items, total 59.97"),
("large-total", "Dee", 1000, 1234.56, "Order {Dee}: 1000 items, total 1234560.00"),
("negative-price", "Refund", 2, -4.5, "Order {Refund}: 2 items, total -9.00"),
]
@pytest.mark.parametrize(("name", "who", "count", "price", "want"), CASES, ids=[c[0] for c in CASES])
def test_describe_order(name, who, count, price, want):
assert describe_order(who, count, price) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
#ifndef ORDER_HPP
#define ORDER_HPP
#include <cstdint>
#include <format>
#include <string>
#include <string_view>
// Returns "Order {name}: count item(s), total count*price". The doubled
// braces are literal braces.
inline std::string describe_order(std::string_view name, std::int64_t count, double price) {
const char* ending = count == 1 ? "" : "s";
return std::format("Order {{{}}}: {} item{}, total {:.2f}", name, count, ending,
static_cast<double>(count) * price);
}
#endif
test_order.cpp 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
#include <cstdint>
#include <cstdio>
#include "order.hpp"
namespace {
struct test_case {
const char* name;
const char* who;
std::int64_t count;
double price;
const char* want;
};
const test_case cases[] = {
{"three-items", "Ada", 3, 1.5, "Order {Ada}: 3 items, total 4.50"},
{"one-item", "Grace", 1, 19.99, "Order {Grace}: 1 item, total 19.99"},
{"many-items", "Linus", 12, 0.25, "Order {Linus}: 12 items, total 3.00"},
{"zero-items", "Ada", 0, 9.99, "Order {Ada}: 0 items, total 0.00"},
{"one-item-plural", "Bob", 1, 0.5, "Order {Bob}: 1 item, total 0.50"},
{"empty-name", "", 2, 1.0, "Order {}: 2 items, total 2.00"},
{"braces-in-name", "{x}", 2, 1.25, "Order {{x}}: 2 items, total 2.50"},
{"percent-in-name", "50% off", 4, 2.5, "Order {50% off}: 4 items, total 10.00"},
{"dollar-in-name", "${HOME}", 1, 3.0, "Order {${HOME}}: 1 item, total 3.00"},
{"product-rounds", "Cy", 3, 19.99, "Order {Cy}: 3 items, total 59.97"},
{"large-total", "Dee", 1000, 1234.56, "Order {Dee}: 1000 items, total 1234560.00"},
{"negative-price", "Refund", 2, -4.5, "Order {Refund}: 2 items, total -9.00"},
};
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
const std::string got = describe_order(c.who, c.count, c.price);
if (got != c.want) {
std::printf("FAIL %s: got \"%s\"\n", c.name, got.c_str());
++failures;
}
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
import java.util.Locale;
/** A sentence built from the values of an order. */
public final class Order {
private Order() {}
/**
* Returns "Order {name}: count item(s), total count*price". Java has no
* string interpolation, so this uses String.format. Locale.ROOT keeps the
* decimal point a dot.
*/
public static String describeOrder(String name, long count, double price) {
String ending = count == 1 ? "" : "s";
return String.format(Locale.ROOT, "Order {%s}: %d item%s, total %.2f", name, count, ending, count * price);
}
public static void main(String[] args) {
System.out.println(describeOrder("Ada", 3, 1.5));
}
}
OrderTest.java 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class OrderTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("three-items", "Ada", 3, 1.5, "Order {Ada}: 3 items, total 4.50"),
Arguments.of("one-item", "Grace", 1, 19.99, "Order {Grace}: 1 item, total 19.99"),
Arguments.of("many-items", "Linus", 12, 0.25, "Order {Linus}: 12 items, total 3.00"),
Arguments.of("zero-items", "Ada", 0, 9.99, "Order {Ada}: 0 items, total 0.00"),
Arguments.of("one-item-plural", "Bob", 1, 0.5, "Order {Bob}: 1 item, total 0.50"),
Arguments.of("empty-name", "", 2, 1.0, "Order {}: 2 items, total 2.00"),
Arguments.of("braces-in-name", "{x}", 2, 1.25, "Order {{x}}: 2 items, total 2.50"),
Arguments.of("percent-in-name", "50% off", 4, 2.5, "Order {50% off}: 4 items, total 10.00"),
Arguments.of("dollar-in-name", "${HOME}", 1, 3.0, "Order {${HOME}}: 1 item, total 3.00"),
Arguments.of("product-rounds", "Cy", 3, 19.99, "Order {Cy}: 3 items, total 59.97"),
Arguments.of("large-total", "Dee", 1000, 1234.56, "Order {Dee}: 1000 items, total 1234560.00"),
Arguments.of("negative-price", "Refund", 2, -4.5, "Order {Refund}: 2 items, total -9.00")
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void describeOrder(String name, String who, long count, double price, String want) {
assertEquals(want, Order.describeOrder(who, count, price));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
#include "order.h"
#include <stdio.h>
int describe_order(char *out, size_t size, const char *name, long long count, double price) {
const char *ending = count == 1 ? "" : "s";
return snprintf(out, size, "Order {%s}: %lld item%s, total %.2f", name, count, ending, (double)count * price);
}
order.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
#ifndef ORDER_H
#define ORDER_H
#include <stddef.h>
// Writes "Order {name}: count item(s), total count*price" into out. Returns
// the length of the full text, as snprintf does. If the result is size or
// more, the text was cut to fit the buffer.
int describe_order(char *out, size_t size, const char *name, long long count, double price);
#endif
test_order.c 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
#include "order.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test_case {
const char *name;
const char *who;
long long count;
double price;
const char *want;
};
static const struct test_case cases[] = {
{"three-items", "Ada", 3, 1.5, "Order {Ada}: 3 items, total 4.50"},
{"one-item", "Grace", 1, 19.99, "Order {Grace}: 1 item, total 19.99"},
{"many-items", "Linus", 12, 0.25, "Order {Linus}: 12 items, total 3.00"},
{"zero-items", "Ada", 0, 9.99, "Order {Ada}: 0 items, total 0.00"},
{"one-item-plural", "Bob", 1, 0.5, "Order {Bob}: 1 item, total 0.50"},
{"empty-name", "", 2, 1.0, "Order {}: 2 items, total 2.00"},
{"braces-in-name", "{x}", 2, 1.25, "Order {{x}}: 2 items, total 2.50"},
{"percent-in-name", "50% off", 4, 2.5, "Order {50% off}: 4 items, total 10.00"},
{"dollar-in-name", "${HOME}", 1, 3.0, "Order {${HOME}}: 1 item, total 3.00"},
{"product-rounds", "Cy", 3, 19.99, "Order {Cy}: 3 items, total 59.97"},
{"large-total", "Dee", 1000, 1234.56, "Order {Dee}: 1000 items, total 1234560.00"},
{"negative-price", "Refund", 2, -4.5, "Order {Refund}: 2 items, total -9.00"},
};
int main(void) {
int failures = 0;
char buf[128];
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
int n = describe_order(buf, sizeof buf, c->who, c->count, c->price);
if (n != (int)strlen(c->want) || strcmp(buf, c->want) != 0) {
printf("FAIL %s: got \"%s\"\n", c->name, buf);
failures++;
}
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
using System.Globalization;
/// <summary>A sentence built from the values of an order.</summary>
public static class Order
{
/// <summary>
/// Returns "Order {name}: count item(s), total count*price". The doubled
/// braces are literal braces, the conditional is in parentheses, and the
/// invariant culture keeps the decimal point a dot.
/// </summary>
public static string DescribeOrder(string name, long count, double price) =>
string.Create(
CultureInfo.InvariantCulture,
$"Order {{{name}}}: {count} item{(count == 1 ? "" : "s")}, total {count * price:F2}");
}
OrderTests.cs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
using Xunit;
public sealed class OrderTests
{
public static TheoryData<string, string, long, double, string> Cases => new()
{
{ "three-items", "Ada", 3, 1.5, "Order {Ada}: 3 items, total 4.50" },
{ "one-item", "Grace", 1, 19.99, "Order {Grace}: 1 item, total 19.99" },
{ "many-items", "Linus", 12, 0.25, "Order {Linus}: 12 items, total 3.00" },
{ "zero-items", "Ada", 0, 9.99, "Order {Ada}: 0 items, total 0.00" },
{ "one-item-plural", "Bob", 1, 0.5, "Order {Bob}: 1 item, total 0.50" },
{ "empty-name", "", 2, 1.0, "Order {}: 2 items, total 2.00" },
{ "braces-in-name", "{x}", 2, 1.25, "Order {{x}}: 2 items, total 2.50" },
{ "percent-in-name", "50% off", 4, 2.5, "Order {50% off}: 4 items, total 10.00" },
{ "dollar-in-name", "${HOME}", 1, 3.0, "Order {${HOME}}: 1 item, total 3.00" },
{ "product-rounds", "Cy", 3, 19.99, "Order {Cy}: 3 items, total 59.97" },
{ "large-total", "Dee", 1000, 1234.56, "Order {Dee}: 1000 items, total 1234560.00" },
{ "negative-price", "Refund", 2, -4.5, "Order {Refund}: 2 items, total -9.00" },
};
[Theory]
[MemberData(nameof(Cases))]
public void DescribeOrder(string name, string who, long count, double price, string want)
{
Assert.NotNull(name);
Assert.Equal(want, Order.DescribeOrder(who, count, price));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
/**
* Returns "Order {name}: count item(s), total count*price". A single brace
* needs no escape in a template literal. The total has 2 decimals.
*/
export function describeOrder(name, count, price) {
return `Order {${name}}: ${count} item${count === 1 ? "" : "s"}, total ${(count * price).toFixed(2)}`;
}
order.test.js 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { describeOrder } from "./order.js";
const cases = [
["three-items", "Ada", 3, 1.5, "Order {Ada}: 3 items, total 4.50"],
["one-item", "Grace", 1, 19.99, "Order {Grace}: 1 item, total 19.99"],
["many-items", "Linus", 12, 0.25, "Order {Linus}: 12 items, total 3.00"],
["zero-items", "Ada", 0, 9.99, "Order {Ada}: 0 items, total 0.00"],
["one-item-plural", "Bob", 1, 0.5, "Order {Bob}: 1 item, total 0.50"],
["empty-name", "", 2, 1, "Order {}: 2 items, total 2.00"],
["braces-in-name", "{x}", 2, 1.25, "Order {{x}}: 2 items, total 2.50"],
["percent-in-name", "50% off", 4, 2.5, "Order {50% off}: 4 items, total 10.00"],
["dollar-in-name", "${HOME}", 1, 3, "Order {${HOME}}: 1 item, total 3.00"],
["product-rounds", "Cy", 3, 19.99, "Order {Cy}: 3 items, total 59.97"],
["large-total", "Dee", 1000, 1234.56, "Order {Dee}: 1000 items, total 1234560.00"],
["negative-price", "Refund", 2, -4.5, "Order {Refund}: 2 items, total -9.00"],
];
for (const [name, who, count, price, want] of cases) {
test(name, () => {
assert.equal(describeOrder(who, count, price), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
/**
* Returns "Order {name}: count item(s), total count*price". A single brace
* needs no escape in a template literal. The total has 2 decimals.
*/
export function describeOrder(name: string, count: number, price: number): string {
return `Order {${name}}: ${count} item${count === 1 ? "" : "s"}, total ${(count * price).toFixed(2)}`;
}
order.test.ts 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { describeOrder } from "./order.ts";
const cases: [string, string, number, number, string][] = [
["three-items", "Ada", 3, 1.5, "Order {Ada}: 3 items, total 4.50"],
["one-item", "Grace", 1, 19.99, "Order {Grace}: 1 item, total 19.99"],
["many-items", "Linus", 12, 0.25, "Order {Linus}: 12 items, total 3.00"],
["zero-items", "Ada", 0, 9.99, "Order {Ada}: 0 items, total 0.00"],
["one-item-plural", "Bob", 1, 0.5, "Order {Bob}: 1 item, total 0.50"],
["empty-name", "", 2, 1, "Order {}: 2 items, total 2.00"],
["braces-in-name", "{x}", 2, 1.25, "Order {{x}}: 2 items, total 2.50"],
["percent-in-name", "50% off", 4, 2.5, "Order {50% off}: 4 items, total 10.00"],
["dollar-in-name", "${HOME}", 1, 3, "Order {${HOME}}: 1 item, total 3.00"],
["product-rounds", "Cy", 3, 19.99, "Order {Cy}: 3 items, total 59.97"],
["large-total", "Dee", 1000, 1234.56, "Order {Dee}: 1000 items, total 1234560.00"],
["negative-price", "Refund", 2, -4.5, "Order {Refund}: 2 items, total -9.00"],
];
for (const [name, who, count, price, want] of cases) {
test(name, () => {
assert.equal(describeOrder(who, count, price), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
// Package order builds a sentence from the values of an order.
package order
import "fmt"
// DescribeOrder returns "Order {name}: count item(s), total count*price".
// Go has no string interpolation, so this uses fmt.Sprintf.
func DescribeOrder(name string, count int64, price float64) string {
ending := "s"
if count == 1 {
ending = ""
}
return fmt.Sprintf("Order {%s}: %d item%s, total %.2f", name, count, ending, float64(count)*price)
}
order_test.go 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
package order
import "testing"
var cases = []struct {
name string
who string
count int64
price float64
want string
}{
{"three-items", "Ada", 3, 1.5, "Order {Ada}: 3 items, total 4.50"},
{"one-item", "Grace", 1, 19.99, "Order {Grace}: 1 item, total 19.99"},
{"many-items", "Linus", 12, 0.25, "Order {Linus}: 12 items, total 3.00"},
{"zero-items", "Ada", 0, 9.99, "Order {Ada}: 0 items, total 0.00"},
{"one-item-plural", "Bob", 1, 0.5, "Order {Bob}: 1 item, total 0.50"},
{"empty-name", "", 2, 1.0, "Order {}: 2 items, total 2.00"},
{"braces-in-name", "{x}", 2, 1.25, "Order {{x}}: 2 items, total 2.50"},
{"percent-in-name", "50% off", 4, 2.5, "Order {50% off}: 4 items, total 10.00"},
{"dollar-in-name", "${HOME}", 1, 3.0, "Order {${HOME}}: 1 item, total 3.00"},
{"product-rounds", "Cy", 3, 19.99, "Order {Cy}: 3 items, total 59.97"},
{"large-total", "Dee", 1000, 1234.56, "Order {Dee}: 1000 items, total 1234560.00"},
{"negative-price", "Refund", 2, -4.5, "Order {Refund}: 2 items, total -9.00"},
}
func TestDescribeOrder(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := DescribeOrder(c.who, c.count, c.price); got != c.want {
t.Fatalf("DescribeOrder(%q, %d, %v) = %q, want %q", c.who, c.count, c.price, got, c.want)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
/// Returns "Order {name}: count item(s), total count*price". A name in
/// braces must be a variable, so the ending and the total come first.
pub fn describe_order(name: &str, count: i64, price: f64) -> String {
let ending = if count == 1 { "" } else { "s" };
let total = count as f64 * price;
format!("Order {{{name}}}: {count} item{ending}, total {total:.2}")
}
tests/order_test.rs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
use algo_interpolate_values_into_a_string::describe_order;
const CASES: &[(&str, &str, i64, f64, &str)] = &[
("three-items", "Ada", 3, 1.5, "Order {Ada}: 3 items, total 4.50"),
("one-item", "Grace", 1, 19.99, "Order {Grace}: 1 item, total 19.99"),
("many-items", "Linus", 12, 0.25, "Order {Linus}: 12 items, total 3.00"),
("zero-items", "Ada", 0, 9.99, "Order {Ada}: 0 items, total 0.00"),
("one-item-plural", "Bob", 1, 0.5, "Order {Bob}: 1 item, total 0.50"),
("empty-name", "", 2, 1.0, "Order {}: 2 items, total 2.00"),
("braces-in-name", "{x}", 2, 1.25, "Order {{x}}: 2 items, total 2.50"),
("percent-in-name", "50% off", 4, 2.5, "Order {50% off}: 4 items, total 10.00"),
("dollar-in-name", "${HOME}", 1, 3.0, "Order {${HOME}}: 1 item, total 3.00"),
("product-rounds", "Cy", 3, 19.99, "Order {Cy}: 3 items, total 59.97"),
("large-total", "Dee", 1000, 1234.56, "Order {Dee}: 1000 items, total 1234560.00"),
("negative-price", "Refund", 2, -4.5, "Order {Refund}: 2 items, total -9.00"),
];
#[test]
fn cases() {
for &(name, who, count, price, want) in CASES {
assert_eq!(describe_order(who, count, price), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
# describe_order name count price: print "Order {name}: count item(s), total
# count*price". Bash has no float arithmetic, so awk computes the total.
describe_order() {
local name=$1 count=$2 price=$3 ending=s total
if ((count == 1)); then
ending=
fi
total=$(LC_ALL=C awk -v c="$count" -v p="$price" 'BEGIN { printf "%.2f", c * p }')
printf '%s\n' "Order {${name}}: ${count} item${ending}, total ${total}"
}
test_order.bats 67 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/interpolate-values-into-a-string/.
setup() {
source "$BATS_TEST_DIRNAME/order.sh"
}
@test "three-items" {
run describe_order 'Ada' 3 1.5
[ "$output" = 'Order {Ada}: 3 items, total 4.50' ]
}
@test "one-item" {
run describe_order 'Grace' 1 19.99
[ "$output" = 'Order {Grace}: 1 item, total 19.99' ]
}
@test "many-items" {
run describe_order 'Linus' 12 0.25
[ "$output" = 'Order {Linus}: 12 items, total 3.00' ]
}
@test "zero-items" {
run describe_order 'Ada' 0 9.99
[ "$output" = 'Order {Ada}: 0 items, total 0.00' ]
}
@test "one-item-plural" {
run describe_order 'Bob' 1 0.5
[ "$output" = 'Order {Bob}: 1 item, total 0.50' ]
}
@test "empty-name" {
run describe_order '' 2 1
[ "$output" = 'Order {}: 2 items, total 2.00' ]
}
@test "braces-in-name" {
run describe_order '{x}' 2 1.25
[ "$output" = 'Order {{x}}: 2 items, total 2.50' ]
}
@test "percent-in-name" {
run describe_order '50% off' 4 2.5
[ "$output" = 'Order {50% off}: 4 items, total 10.00' ]
}
@test "dollar-in-name" {
run describe_order '${HOME}' 1 3
[ "$output" = 'Order {${HOME}}: 1 item, total 3.00' ]
}
@test "product-rounds" {
run describe_order 'Cy' 3 19.99
[ "$output" = 'Order {Cy}: 3 items, total 59.97' ]
}
@test "large-total" {
run describe_order 'Dee' 1000 1234.56
[ "$output" = 'Order {Dee}: 1000 items, total 1234560.00' ]
}
@test "negative-price" {
run describe_order 'Refund' 2 -4.5
[ "$output" = 'Order {Refund}: 2 items, total -9.00' ]
}
References
- Rosetta Code, String interpolation (included) (task text, from acmeism/RosettaCodeData), task text
- PEP 498, Literal String Interpolation, Abstract; Specification
- Template literals, MDN Web Docs, Description
- String interpolation using $, C# reference, Special characters
- Package fmt, The Go Standard Library, Overview
- Module std::fmt, The Rust Standard Library, Named parameters; Escaping
- Double Quotes, Bash Reference Manual, 3.1.2.3
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag VX3ENF Edit this page History Report an error Markdown