manyspikes

String interpolation

Initialising environment...

In the previous exercise, we looked at composing a large string by combining smaller strings with the help of string operators.

level = "info" msg = "process completed successfully" log_record = level.upper() + ": " + msg.capitalize() + "."

In the snippet above we are combining multiple strings using the + operator, but Python has a better mechanism for doing this. It is called string interpolation.

String interpolation allows you to embed strings into other strings, without having to concatenate multiple substrings with the + operator. Here is how it works:

name = "Jane" introduction = f"Hi! My name is {name}." print(introduction) # This would print "Hi! My name is Jane."

To use string interpolation, you prepend an f to the string you want to embed values in, and within the string you refer to the variables to be embedded by placing them within curly braces {...}.

This method works not only for strings, but also for other types that can be converted to a string. For instance, the following snippet is valid:

name = "Jane" age = 27 # Note: this is an integer! introduction = f"Hi! My name is {name} and I am {age} years old." print(introduction) # This would print "Hi! My name is Jane and I am 27 years old."

Instructions

Define the following variables:

level = "info" msg = "process completed successfully"

Using string interpolation, produce the following string and assign it to a variable called log_record:

"INFO: Process completed successfully."