Formatting
# Using `%` and `.format()` in Python
## Introduction
In Python, formatting strings is a common task. Two popular methods to do this are using the `%` operator and the `.format()` method. Let's understand how to use them with simple examples.
## The `%` Operator
The `%` operator is a traditional way to format strings. It places values in a string using placeholders.
### Example:
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
Output: My name is Alice and I am 30 years old.
Here, `%s` is a placeholder for a string, and `%d` is a placeholder for an integer.
### More Placeholders:
- `%s` - String
- `%d` - Integer
- `%f` - Floating-point number
## The `.format()` Method
The `.format()` method is more flexible and was introduced in Python 3. It uses curly braces `{}` as placeholders in a string.
### Example:
name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
Output: My name is Bob and I am 25 years old.
Here, `{}` are placeholders that get replaced by values passed to the `format()` method.
### Using Index Numbers:
You can specify the order of values using index numbers inside `{}`.
#### Example:
formatted_string = "My name is {0} and I am {1} years old. {0} loves coding.".format(name, age)
print(formatted_string)
Output: My name is Bob and I am 25 years old. Bob loves coding.
### Using Keywords:
You can also use keywords to make the code more readable.
#### Example:
formatted_string = "My name is {name} and I am {age} years old.".format(name="Charlie", age=22)
print(formatted_string)
Output: My name is Charlie and I am 22 years old.
## Conclusion
Both `%` and `.format()` are useful for formatting strings in Python. The `%` operator is simple and good for basic formatting. The `.format()` method is more powerful and flexible for more complex string formatting needs.
Happy coding!