Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to demonstrate the string interpolation
In Python, we can demonstrate string interpolation using f-strings, the % operator, and the format() method. String interpolation is the process of inserting dynamic data or variables into a string, making it useful for creating formatted strings without manual concatenation.
Method 1: Using f-strings
An f-string is a string literal that starts with f or F. The prefix indicates that the string contains expressions enclosed in curly braces {}, which are evaluated at runtime.
Example
Here we create variables and use an f-string to interpolate their values into a formatted message ?
name = 'John'
age = 25
height = 1.75
message = f"My name is {name}. I am {age} years old and {height} meters tall."
print(message)
The output of the above code is ?
My name is John. I am 25 years old and 1.75 meters tall.
Method 2: Using the format() Method
The format() method uses placeholders represented by curly braces {} in the string. Values are passed as arguments to the format() method.
Example
We create a string with placeholders and use format() to specify the values ?
name = 'John'
age = 25
height = 1.75
message = "My name is {}. I am {} years old and {} meters tall.".format(name, age, height)
print(message)
The output of the above code is ?
My name is John. I am 25 years old and 1.75 meters tall.
Method 3: Using the % Operator
The % operator works similar to printf() in C programming. It uses format specifiers like %s (string), %d (integer), and %f (float) to specify the data type of each placeholder.
Example
We use format specifiers and pass values as a tuple to the % operator ?
name = 'John' age = 25 height = 1.75 message = "My name is %s. I am %d years old and %.2f meters tall." % (name, age, height) print(message)
The output of the above code is ?
My name is John. I am 25 years old and 1.75 meters tall.
Comparison of Methods
| Method | Syntax | Performance | Recommended For |
|---|---|---|---|
| f-strings | f"{variable}" |
Fastest | Python 3.6+ (preferred) |
| format() | "{}.format(value)" |
Moderate | Complex formatting |
| % operator | "%s" % value |
Slower | Legacy code compatibility |
Conclusion
String interpolation in Python can be achieved using f-strings, format(), or the % operator. F-strings are the preferred method for Python 3.6+ due to their readability and performance. Choose the method that best fits your Python version and formatting requirements.
