String Formatting
String Formatting
In Python, string formatting can be done in several ways. Here's an overview of different methods, along
with examples of each:
python
Copy code
name = "John"
age = 25
python
Copy code
name = "John"
age = 25
python
Copy code
Or named arguments:
python
Copy code
python
Copy code
name = "John"
age = 25
You can also format numbers, for example, rounding floats or adding leading zeros:
python
Copy code
price = 49.99
number = 7
print("The number is {:03}".format(number)) # Prints the number with leading zeros (e.g., 007)
Or using f-strings:
python
Copy code
price = 49.99
number = 7
python
Copy code
python
Copy code
name = "Alice"
age = 30
balance = 1023.456
# Using % operator
# Using f-strings
Each method has its use cases, but f-strings are currently the most concise and recommended for
modern Python.