Embedding values in strings
In the contents of this course, you have learned about the data type called String, which describes values containing text. Up to this point we have only ever created strings with set contents. Also, you have not yet been shown a way to write values other than strings to the screen using the print function. In this chapter, we will take a look at how to dynamically create strings which contain other values. The following program prompts the user to input their name, after which a greeting with the user's name is emitted.
Input:
Output:
As you can see from the above example, we can embed values into strings by using a special syntax. Inside the string, a dollar sign is placed, immediately followed by a set of curly braces that enclose an expression. The dollar sign, as well as the curly braces, are replaced by the value that the expression evaluates to.
In some rare cases you may want to circumvent the replacement and instead create a string that literally contains the dollar sign, the curly braces as well as the enclosed expression. To achieve this, you can use the following trick where a string with just a dollar sign is embedded into another string. The example below shows that the replacement does not occur in this case. This happens because, for the replacement to succeed, the replacement pattern (or parts of it) cannot be embedded itself.
Output: