String interpolation (included)

Revision as of 07:21, 30 January 2010 by rosettacode>Paddy3118 (New draft task and Python solution.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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.

String interpolation (included) is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

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

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>