String interpolation (included)
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
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.
- For example, given an original string of
"Mary had a X lamb."
, a value of "big", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string"Mary had a big lamb"
.
- (Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X").
The task is to use your languages inbuilt string interpolation abilities to interpolate a string missing the text "little"
which is held in a variable, to produce the output string "Mary had a little lamb"
.
Note: The task is not to create a string interpolation routine, but to show a languages built-in capability.
Python
Python has more than one inbuilt way of accomplishing the task. The methods have different capabilities that are not exercised by this small task
Using the % string interpolation operator: <lang python>>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'</lang>
Using the .format method of strings: <lang python>>>> original = 'Mary had a {extra} lamb.' >>> extra = 'little' >>> original.format(**locals()) 'Mary had a little lamb.'</lang>
Using the Template class of the string module: <lang python>>>> from string import Template >>> original = Template('Mary had a $extra lamb.') >>> extra = 'little' >>> original.substitute(**locals()) 'Mary had a little lamb.'</lang>