Strings are fundamental building blocks in Python, used to represent text data. They are enclosed in either single quotes ('), double quotes ("), or triple quotes (""" or '''). Here's a basic example:
name = "Alice" greeting = "Hello, " + name + "!" print(greeting) # Output: Hello, Alice!
Formatted Strings (f-strings):
f-strings (introduced in Python 3.6) offer a powerful and concise way to format strings by embedding expressions directly within them. Here's how they work:
age = 30 message = f"Happy {age}th birthday, {name}!" print(message) # Output: Happy 30th birthday, Alice!
Advantages of f-strings:
- Readability: Code becomes more readable as expressions are placed directly within the string.
- Flexibility: You can format various data types (numbers, strings, booleans) within f-strings.
- Conciseness: f-strings eliminate the need for string concatenation (+) for simple formatting.
Advanced f-string features:
- f-string expressions: Use curly braces {} to include expressions within the string.
- Formatting options: You can format numbers (e.g., specify decimal places), strings (e.g., uppercase), and dates within f-strings.
- f-string alignment: Control alignment (left, right, center) and padding for numeric values.
Here's an example showcasing some features:
price = 12.99 formatted_price = f"Price: ₹{price:.2f}" # Format price with 2 decimal places print(formatted_price) # Output: Price: ₹12.99 name = "Bob" centered_name = f"{name:^20}" # Center align name within 20 characters print(centered_name) # Output: Bob
When to Use f-strings vs. Traditional String Formatting:
- Use f-strings for simple formatting and embedding expressions within the string.
- For complex formatting tasks (e.g., custom date formatting), consider the format() method or third-party libraries like formatstring.
Mastering strings and formatted strings is essential for working with text data in Python. By effectively using these features, you can create clear, readable, and well-formatted code.