Variables and constants in Python

Using variables

Single and double quote marks can be used interchangeably to define strings. In Python, if you enclose a string within single or double quotes, the string itself is treated literally, without any variable interpolation or expression evaluation.

Variable interpolation is a process in programming where variables or expressions are embedded within strings, allowing their values to be directly inserted into the string. It's like creating a template where certain placeholders are replaced with the actual values of variables when the string is evaluated or printed.

To achieve variable interpolation or expression evaluation in Python, you would typically use f-strings (formatted string literals) or the .format() method.

What is an f-string?

An f-string (formatted string) allows you to embed expressions inside string literals, using curly braces {} to include variables or expressions that will be evaluated and inserted into the string. They are preceded by the letter f.

Run the following code

Using f-strings for variable interpolation:

message = 'hello, world!'
print('print message with double quotes around it')
print(f'"{message}"')
print('')

Using .format() method for variable interpolation:

message = 'hello, world!'
print('print message with double quotes around it')
print('"{}"'.format(message))
print('')