smartyfy.mrindigi.com

Python Master Course V2 — 007. Strings and Text Fundamentals

Module 01 · Python foundations · Lesson 007 / 200

Strings and Text Fundamentals

Outcome: Build accurate text-processing programs, work with multilingual Unicode data, produce formatted reports, debug text errors, and create reusable, validated utility functions.

In this lesson · 15 sections + self-check
  1. Video lesson — dedicated player area
  2. Learning objectives and prerequisites
  3. 1. Understanding Python strings
  4. 2. Indexing and slicing
  5. 3. Immutability, concatenation and membership
  6. 4. Everyday string methods
  7. 5. Text formatting for professional reports
  8. 6. Unicode and bytes: essential for Indian languages
  9. 7. Validation and debugging
  10. 8. Guided project — Student progress report formatter
  11. 9. Professional best practices
  12. 10. Guided practice and independent exercises
  13. 11. Advanced independent challenge
  14. 12. Knowledge check
  15. Lesson summary
  16. Interactive self-check

Video lesson — dedicated player area

▶ Video URL and player/embed will be placed here after the lesson recording is available. No recording has been uploaded yet.

Suggested recording chapters: string concepts, slicing, methods, text formatting, Unicode/encoding, and a guided mini-project.

Learning objectives and prerequisites

Prerequisites: complete Lessons 001–006, install Python 3 and be able to run a Python file. After this lesson you should be able to declare strings, work with indexes and slices, explain immutability, use built-in text methods, format dynamic output, compare Unicode text responsibly, distinguish text from bytes, and validate user-supplied text.

1. Understanding Python strings

A Python str stores an immutable sequence of Unicode code points. It is intended for textual information: names, messages, course titles, labels and descriptions. A displayed symbol can be composed of multiple code points. This distinction becomes important for Telugu text, accented letters and emoji.

Example 01 — Creating text

course = "Python Master Course V2"
telugu = "తెలుగు"
greeting = 'Hello, learner!'
blank = ""
print(course)
print(telugu)
print(type(greeting).__name__)  # str
print(len(blank))             # 0

Single and double quotes are equivalent. Use triple quotes for strings spanning multiple lines. Use descriptive variable names rather than single-letter abbreviations for business text.

Example 02 — Escapes and multiline strings

line = "First line\nSecond line"
table = "Name\tScore"
message = """Study the concept.
Run the examples.
Complete the project."""
print(line)
print(table)
print(message)

n means a newline, t means a tab, and \ represents a literal backslash. Use repr() to inspect invisible formatting characters during debugging.

2. Indexing and slicing

Python indexing starts at zero. Negative indexes count from the end. A slice uses text[start:stop:step], with the stop index excluded.

Example 03 — Read individual positions

word = "Python"
print(word[0])   # P
print(word[2])   # t
print(word[-1])  # n
print(len(word)) # 6

Example 04 — Extract sections

word = "Python"
print(word[:3])    # Pyt
print(word[2:])    # thon
print(word[::2])   # Pto
print(word[::-1])  # nohtyP

Direct indexing of a missing position raises IndexError; slicing beyond the string length simply produces the available portion. For multilingual text, slicing is based on code points, not necessarily human-visible characters.

Example 05 — Defensive indexing

student_code = ""
if student_code:
    print(student_code[0])
else:
    print("Missing student code")

3. Immutability, concatenation and membership

Strings cannot be altered at an existing position: methods such as replace() and upper() return new string values. Save the returned result when you intend to keep a change.

Example 06 — Build a new value

name = "python"
improved = name.capitalize()
print(name)      # python
print(improved)  # Python
course_name = improved + " Master Course"
print("Master" in course_name)  # True

For large volumes of pieces, accumulate them into a list and combine them with "".join(pieces), rather than repeatedly rebuilding large strings.

4. Everyday string methods

strip() removes surrounding whitespace, split() separates text, join() combines elements, replace() substitutes substrings, and startswith()/endswith() help validate formats.

Example 07 — Clean and split data

raw = "  Python, Data, AI  "
parts = [item.strip() for item in raw.strip().split(",")]
print(parts)             # ['Python', 'Data', 'AI']
print(" | ".join(parts)) # Python | Data | AI

Do not use naive comma splitting for production CSV files because quoted fields can contain commas. Use the Python standard-library csv reader for structured CSV.

Example 08 — Find and replace

status = "request pending"
print(status.find("pending"))            # 8
print(status.find("approved"))           # -1
print(status.replace("pending", "done"))  # request done
print(status.startswith("request"))      # True

find() returns -1 when absent, whereas index() raises ValueError. Choose deliberately.

Example 09 — Normalize extra spaces

sentence = "  Learning    Python \t takes practice  "
print(" ".join(sentence.split()))
# Learning Python takes practice

Compressing whitespace can be useful for simple labels, but it may be inappropriate for source code, poetry, addresses or formatted documents.

5. Text formatting for professional reports

Modern Python f-strings are convenient for combining variables with a display template. Formatting creates a presentation string; it does not rewrite the source numeric value.

Example 10 — Readable progress status

name = "Ananya"
completed = 7
total = 200
percentage = completed / total * 100
print(f"Welcome, {name}")
print(f"Progress: {completed}/{total}")
print(f"Completion: {percentage:.2f}%")
print(f"{'Topic':<14} {'Count':>6}")
print(f"{'Python':<14} {completed:>6}")

The output percentage is 3.50%. :.2f displays two decimal places, < left-aligns and > right-aligns. For financial amounts, use decimal.Decimal rather than assuming ordinary floats represent decimals exactly.

Example 11 — Reporting date and currency

from datetime import date
from decimal import Decimal

today = date(2026, 10, 8)
amount = Decimal("1250.50")
print(f"Generated: {today:%d %b %Y}")
print(f"Amount: ₹{amount:,.2f}")

6. Unicode and bytes: essential for Indian languages

str contains Unicode text, while bytes contains raw bytes. When exporting, storing or transmitting data, encode to a known format such as UTF-8 and decode using the same format. Byte length and string length can be different.

Example 12 — UTF-8 round-trip

text = "నమస్కారం"
encoded = text.encode("utf-8")
restored = encoded.decode("utf-8")
print(text == restored)    # True
print(type(encoded).__name__) # bytes
print(len(encoded), len(text))

Example 13 — Canonical Unicode normalization

import unicodedata

one = "\u00e9"
two = "e\u0301"
print(one == two)  # False
print(unicodedata.normalize("NFC", one) ==
      unicodedata.normalize("NFC", two)) # True

Two strings can appear identical on screen even when their underlying code points differ. Unicode normalization is useful when comparing imported data. Preserve the human-readable original when exact display matters.

Example 14 — Better caseless matching

left = "Straße"
right = "STRASSE"
print(left.lower() == right.lower())        # False
print(left.casefold() == right.casefold())  # True

casefold() is intended for general Unicode caseless matching, though fully language-aware search needs additional techniques. Do not silently change people’s names or identifiers merely for display.

7. Validation and debugging

Validate inputs before using them. A string containing only spaces is truthy, so checking bool(raw_name) does not establish a meaningful non-empty name.

Example 15 — Reject blank text

name = "   "
if not name.strip():
    print("Enter a non-blank name")
else:
    print("Hello", name.strip())

Example 16 — Validate a course code

code = "PY-007"
prefix, separator, number = code.partition("-")
valid = (
    separator == "-"
    and prefix == "PY"
    and len(number) == 3
    and number.isascii()
    and number.isdigit()
)
print(valid)  # True

Professional troubleshooting sequence: reproduce with a minimal input, inspect repr(value) for hidden whitespace, examine type(value), compare expected and actual output, then write tests around edge cases.

Common errors and fixes

  • IndexError: Do not index an empty string; check its length.
  • TypeError: Strings are immutable; create a new value instead of assigning to a character position.
  • Unexpected concatenation: input() returns str. Convert validated digits with int() before arithmetic.
  • Invisible spaces: Inspect repr(), then use strip() when appropriate.
  • Visually matching text compares unequal: Inspect Unicode normalization and casing.
  • Invalid bytes: Check the original encoding; do not guess or silently discard decoding errors.

8. Guided project — Student progress report formatter

Business scenario: Generate a neat progress report from student input. Requirements: validate lesson counts, reject blank text fields, preserve display names, normalize Unicode consistently, and format completion percentage to two decimal places.

Complete runnable Python project

from decimal import Decimal
import unicodedata

def progress_report(student, course, completed, total):
    if not isinstance(student, str) or not isinstance(course, str):
        raise TypeError("student and course must be text")
    if type(completed) is not int or type(total) is not int:
        raise TypeError("counts must be integers")
    if total <= 0 or completed < 0 or completed > total:
        raise ValueError("invalid progress values")

    student = unicodedata.normalize("NFC", student.strip())
    course = unicodedata.normalize("NFC", course.strip())
    if not student or not course:
        raise ValueError("student and course are required")

    percentage = Decimal(completed) / Decimal(total) * 100
    rows = [
        "=" * 40,
        "SMARTYFY LEARNING REPORT",
        "=" * 40,
        f"Student : {student}",
        f"Course  : {course}",
        f"Lessons : {completed} of {total}",
        f"Progress: {percentage:.2f}%",
        "=" * 40,
    ]
    return "\n".join(rows)

print(progress_report(
    "  Ananya  ", " Python Master Course V2 ", 7, 200
))

Expected result: A bordered text report for Ananya showing 7 of 200 lessons and 3.50% progress. Note that the function returns text rather than printing internally, making it usable in a website, terminal or report file.

Project tests

assert "3.50%" in progress_report("A", "Python", 7, 200)
assert "0.00%" in progress_report("A", "Python", 0, 200)
assert "100.00%" in progress_report("A", "Python", 200, 200)
try:
    progress_report(" ", "Python", 1, 200)
except ValueError as error:
    print("Invalid name correctly rejected:", error)

9. Professional best practices

  • Separate data validation, business calculations and display formatting.
  • For multilingual input, distinguish the original display value from a normalized lookup key.
  • Use explicit encoding at file and API boundaries; prefer UTF-8 when appropriate.
  • Use f-strings for displaying trusted values, but use parameterized queries for database operations.
  • Use specialized escaping when rendering untrusted content in HTML or URLs.
  • Use join() when assembling many pieces of text.
  • Cover empty values, whitespace-only values, non-ASCII input and boundary values in tests.
  • Understand that code-point indexing does not always match a user’s perceived characters.

10. Guided practice and independent exercises

1. Extract 2026 from PY-2026-007 using a slice.

Hint

Find the four year digits by their indices.

Show answer and explanation

The year starts at index 3 and ends before index 7, so the result is 2026. This fixed-position solution assumes the stated code format.

code = "PY-2026-007"
print(code[3:7])

2. Print the first and final letters in a nonempty course title.

Hint

Check that the value has at least one character first.

Show answer and explanation

The first position is 0 and the last is -1. An empty title must be handled before indexing; a one-character title returns the same character for both positions.

title = "Python"
if title:
    print(title[0], title[-1])
else:
    print("Missing title")

3. Transform " python, data, ai " into "Python | Data | Ai" using methods.

Hint

Strip each field, then transform and join the resulting words.

Show answer and explanation

The requested display is Python | Data | Ai. Title-casing gives Ai; if an application requires the acronym AI, it needs a separate display rule rather than assuming title-case preserves acronyms.

text = "  python, data, ai "
parts = [word.strip().title() for word in text.split(",")]
print(" | ".join(parts))

4. Format 37 completed lessons out of 200 to two decimal places.

Hint

Calculate the fraction before formatting its percentage.

Show answer and explanation

37 divided by 200 times 100 is 18.5, displayed as 18.50%. The total must be positive to avoid division by zero.

completed = 37
total = 200
percentage = completed / total * 100
print(f"{percentage:.2f}%")

5. Explain the difference between len(text) and len(text.encode("utf-8")).

Hint

Distinguish code points, encoded bytes, and visible characters.

Show answer and explanation

len(text) counts Unicode code points; encoding to UTF-8 then taking length counts bytes. Telugu code points commonly need multiple UTF-8 bytes. Neither count always equals the number of visible user-perceived characters.

6. Find the difference between lower() and casefold() using a real example.

Hint

Use a word whose caseless form expands characters.

Show answer and explanation

Lowercasing yields False for this comparison; casefolding yields True because ß folds to ss. Keep the original spelling for display.

left = "Straße"
right = "STRASSE"
print(left.lower() == right.lower())
print(left.casefold() == right.casefold())

7. Write a safe blank-name validator and test empty and whitespace-only values.

Hint

Require text, then test the stripped value.

Show answer and explanation

Both empty and whitespace-only strings are rejected. The ordinary name is accepted. Invalid non-text inputs are also rejected by this Boolean validator rather than receiving a string method call.

def valid_name(value):
    return isinstance(value, str) and bool(value.strip())

print(valid_name(""))
print(valid_name("   "))
print(valid_name("Asha"))
print(valid_name(None))

8. Extend the report generator to show a “Completed” label at 100%.

Hint

Compare completed counts rather than a rounded percentage string.

Show answer and explanation

Add status = "Completed" if completed == total else "In progress" after the project’s count validation, then append f"Status : {status}" to its rows. Comparing counts avoids a rounded display such as 100.00% incorrectly labelling an unfinished course.

11. Advanced independent challenge

Multilingual course search: Given titles such as ["Python Basics", " DATA SCIENCE ", "తెలుగు Python", "Straße"], create a function that keeps the original display value while deriving an NFC-normalized, casefolded search key. Support case-insensitive lookup, validate blank queries, and add at least five tests. Explain why this is not a complete language-specific search engine.

Hint

Build one normalized search key for comparison and return the original matching titles for display. Test the query independently of the list.

Show answer and explanation

This implementation uses a normalized caseless substring search, retains original display strings, and rejects non-text or blank queries. It does not provide language-specific stemming, transliteration, ranking, or collation.

import unicodedata

def search_key(text):
    if not isinstance(text, str):
        raise TypeError("Search values must be text")
    return unicodedata.normalize("NFC", text.strip().casefold())

def search_courses(titles, query):
    key = search_key(query)
    if not key:
        raise ValueError("Query must not be blank")
    return [title for title in titles if key in search_key(title)]

titles = ["Python Basics", "  DATA SCIENCE ", "తెలుగు Python", "Straße"]
assert search_courses(titles, "python") == ["Python Basics", "తెలుగు Python"]
assert search_courses(titles, "data science") == ["  DATA SCIENCE "]
assert search_courses(titles, "STRASSE") == ["Straße"]
assert search_courses(titles, "missing") == []
assert search_courses(["e\u0301"], "\u00e9") == ["e\u0301"]
try:
    search_courses(titles, "   ")
except ValueError:
    pass
else:
    raise AssertionError("Blank query must fail")
print("Six search checks passed")

12. Knowledge check

1. Are Python strings mutable? Why does this matter?

Hint

Changing text produces another string value.

Show answer and explanation

Strings are immutable. Methods such as replace() return a new value rather than editing the original object. Assign that result if you want a name to refer to the transformed text.

2. What does a negative index mean?

Hint

Count from the right end.

Show answer and explanation

-1 selects the final character, -2 the previous one. Reading any index from an empty string raises IndexError, so validate a nonempty value before indexing.

3. What is the exclusive end of a slice?

Hint

The stop position is not included.

Show answer and explanation

"Python"[1:4] includes indices 1, 2, and 3, giving “yth”. This exclusive stop makes adjacent slices fit together without repeating the boundary character.

4. When should split() not be used to parse a file format?

Hint

A separator can also appear inside quoted data.

Show answer and explanation

Use a dedicated parser for formats such as CSV, where quoted fields, escaped quotes, and embedded newlines affect separators. A plain split(",") does not implement those format rules.

5. How do f-strings control displayed precision?

Hint

The format specification controls the display.

Show answer and explanation

For a number n, f"{n:.2f}" displays fixed-point text with two decimal places. The formatted result is a string; formatting does not improve the accuracy of the original numeric calculation.

6. How do str and bytes differ?

Hint

Decoding requires an encoding agreement.

Show answer and explanation

str holds Unicode text; bytes holds byte values. Encode text using a stated encoding such as UTF-8, and decode using the same agreement. Byte length can differ from the number of Unicode code points.

7. Why can two visually identical strings compare unequal?

Hint

One visible letter can have multiple code-point representations.

Show answer and explanation

“é” can be a single code point or e followed by a combining acute accent. Their original sequences compare unequal. Normalize both to the same Unicode normalization form when the application intends canonical equivalence.

8. Why is casefold() useful?

Hint

Case conversion can need more than lowercasing.

Show answer and explanation

casefold() supports broad Unicode caseless matching, for example Straße and STRASSE. It is not a full language-specific search, collation, or accent-removal algorithm; preserve the original display text.

9. Why should a report function return text rather than always printing it?

Hint

Returning a value separates computation from presentation.

Show answer and explanation

Returned text can be printed, written to a file, displayed in a UI, or asserted in a test. A function that always prints couples formatting to one output destination and is harder to reuse.

10. What edge cases deserve tests in a text-processing utility?

Hint

Test both missing input and valid boundaries.

Show answer and explanation

Include empty and whitespace-only strings, invalid types, multilingual text, canonically equivalent sequences, and counts at zero and full completion. Also reject negative, excessive, or Boolean counts when the contract expects exact integers.

Lesson summary

You learned to manipulate strings safely, extract and format information, understand immutable text and Unicode, and build a reusable professional progress-report function. The central engineering principle is to separate receiving, validating, transforming and presenting text. Apply the supplied tests before continuing.

Apply what you learned

Interactive self-check

Choose an answer for each question, then check your work. You will see the correct answer and why it is correct.

1. Are Python strings mutable?
2. What does "Python"[0:2] return?
3. What does text.strip() remove?
4. What does "தமிழ்".encode("utf-8") produce?
5. Why return formatted text from a helper function?

This is a practice quiz. Results are saved on this browser when storage is available.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion and quiz results are stored on this browser.