7.3: String Formatting
- Page ID
- 10702
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)
Overview
String formatting uses a process of string interpolation (variable substitution) to evaluate a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.[1]
Discussion
Most current programming languages provide one or more string formatting functions that use a template string with placeholders and optional alignment, width, and precision indicators to generate formatted output.
Language | Function | Examples |
---|---|---|
C++ | snprintf() | snprintf(str, sizeof(str), "Hello %s!", name); |
C# | Format() | String.Format("Hello {0}!", name); |
Java | format() | String.format("Hello %s!", name); |
JavaScript | template literal | `Hello ${name}`; |
Python | format() | "Hello {}!".format(name) |
Swift | interpolationString() | "Hello \(name)!" String(format:"%.2f", value) |
String interpolation, like string concatenation, may lead to security problems. If user input data is improperly escaped or filtered, the system may be exposed to code injection.[2]
Key Terms
- code injection
- The exploitation of a computer bug that is caused by processing invalid data.[3]
- formatting
- Modifying the way the output is displayed.
- string interpolation
- Evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.