Lesson 5.5: String Manipulation and Formatting
Introduction:
Strings are sequences of characters in Python and are widely used to store text data. Mastering string manipulation and formatting is essential for tasks like data processing, reporting, and creating user-friendly outputs.
1. Creating Strings:
-
Strings can be created using single quotes
', double quotes", or triple quotes'''/"""for multi-line strings.
Examples:
2. Accessing and Slicing Strings:
-
Strings are ordered, and characters can be accessed via indexing.
Examples:
3. Common String Methods:
| Method | Description |
|---|---|
upper() |
Converts string to uppercase |
lower() |
Converts string to lowercase |
title() |
Capitalizes first letter of each word |
strip() |
Removes leading/trailing spaces |
replace(old, new) |
Replaces substring |
split(separator) |
Splits string into a list |
join(iterable) |
Joins elements of a list into a string |
find(substring) |
Returns index of first occurrence |
count(substring) |
Counts occurrences of a substring |
Example:
4. String Formatting:
-
Formatting allows dynamic insertion of variables into strings.
Using f-strings (Python 3.6+):
Using format():
Using % operator:
Practical Tips:
-
Use f-strings for readability and efficiency in Python 3.6+
-
Apply string methods to clean and process data before output
-
Remember strings are immutable; operations return new strings
Learning Outcome of This Lesson:
-
Create and access strings efficiently
-
Perform common string manipulations using built-in methods
-
Format strings dynamically using f-strings,
format(), or%operator -
Apply string techniques for real-world data processing and presentation
