Logo OnlineCBT
PYTHON Tutorial
PYTHON · LESSON 8

Strings and Text Processing

Create, index, slice, search and transform text while understanding that Python strings are immutable Unicode sequences.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive
Updated: 26 Jul 2026

Lesson 8: Strings and Text Processing

1. Introduction to Strings in Python

In computer programming, textual data is represented using strings. In Python, a string is an ordered sequence of Unicode characters stored as an instance of the built-in str class. Because Python 3 natively encodes strings in UTF-8, Python strings can handle virtually all world languages, symbols, and emojis effortlessly.

Text processing—ranging from simple user input validation to complex parsing in Natural Language Processing (NLP) and Web Scraping—relies heavily on mastering string manipulation. In this lesson, we will explore string creation, literal escaping, indexing, slicing, immutability, and Python's extensive suite of built-in string methods.


2. String Creation and Escape Sequences

Methods of String Delimitation

Python offers multiple ways to define string literals:

  • Single Quotes (`'...'`): Useful for short strings without single quote apostrophes.
  • Double Quotes (`"..."`): Ideal when the string text contains single quotes (e.g., "Python's power").
  • Triple Quotes (`'''...'''` or `"""..."""`): Preserves multi-line formatting, line breaks, and whitespace exactness without needing escape characters.

Escape Sequences

An escape sequence begins with a backslash (\) and tells the interpreter to treat the following character as a special instruction rather than a literal character.

Escape Sequence Meaning / Action Example Code Rendered Output
\n Newline (Line feed) print("Line 1\nLine 2") Line 1
Line 2
\t Horizontal Tab print("Name:\tAlice") Name:    Alice
\\ Literal Backslash print("C:\\Users\\Main") C:\Users\Main
\' Literal Single Quote print('It\'s working') It's working
\" Literal Double Quote print("He said \"Hi\"") He said "Hi"

Raw Strings (`r"..."`)

When working with Windows file paths or regular expressions (Regex), backslashes can cause unwanted escaping. Prefixing a string with r or R turns it into a Raw String, which ignores all escape sequences and treats backslashes as literal characters.

RAW_STRINGS.PY
# Escaped String vs Raw String
escaped_path = "C:\\new_folder\\test.txt"
raw_path = r"C:\new_folder\test.txt"

print("Escaped Path Output:")
print(escaped_path)
print("\nRaw Path Output:")
print(raw_path)
OUTPUT
Escaped Path Output:
C:\new_folder\test.txt

Raw Path Output:
C:\new_folder\test.txt

3. String Indexing and Immutability

Indexing Mechanics

Because strings are ordered sequences, every character in a string occupies a fixed zero-based position called an index. Python supports both positive (left-to-right) and negative (right-to-left) indexing.

 String:    ' P  y  t  h  o  n '
 Positive:    0  1  2  3  4  5
 Negative:   -6 -5 -4 -3 -2 -1
Index Bounds Rule: Valid positive indices range from 0 to len(string) - 1. Accessing an index outside this range raises an IndexError: string index out of range.

Deep Dive: String Immutability in Memory

Strings in Python are strictly immutable. Once a string object is created, its individual characters cannot be changed, replaced, or deleted in place.

STRING_IMMUTABILITY.PY
sample_str = "Python"
print("First character:", sample_str[0])
print("Last character:", sample_str[-1])

# Attempting in-place modification raises an error:
try:
    sample_str[0] = "J"
except TypeError as err:
    print("Error Caught:", err)

# Correct approach: Create a new string object
new_str = "J" + sample_str[1:]
print("New String Object:", new_str)
OUTPUT
First character: P
Last character: n
Error Caught: 'str' object does not support item assignment
New String Object: Jython

4. Advanced String Slicing

Slicing allows you to extract a substring from a string by specifying a range of indices using the slice notation: string[start:stop:step].

The Slicing Parameters

  • start: The starting index of the slice (inclusive). Defaults to 0 if omitted.
  • stop: The ending index of the slice (exclusive). Defaults to len(string) if omitted.
  • step: The stride increment between characters. Defaults to 1 if omitted.
Slicing Boundaries Safety: Unlike single-character indexing, slicing never raises an IndexError when indices go beyond string boundaries. Python automatically clamps slice indices to the string length.

Slicing Code Demonstrations

STRING_SLICING.PY
text = "Software Engineering"

print("Substring [0:8]   ->", text[0:8])    # Extract first 8 chars
print("Substring [9:]    ->", text[9:])     # From index 9 to end
print("Substring [:8]    ->", text[:8])     # From start to index 8
print("Step Slicing [::2]->", text[::2])    # Every second character
print("Reversed String  ->", text[::-1])   # Step of -1 reverses string!
OUTPUT
Substring [0:8]   -> Software
Substring [9:]    -> Engineering
Substring [:8]    -> Software
Step Slicing [::2]-> Sftar Eninrn
Reversed String  -> gnireenignE erawtfoS

5. Comprehensive Reference: Built-in String Methods

Because strings are instances of the str class, Python provides dozens of built-in methods. Methods do not modify the original string—they return a new transformed string object.

1. Case Transformation Methods

Method Name Description Example Code Output
.lower() Converts all characters to lowercase. "PyThOn".lower() "python"
.upper() Converts all characters to uppercase. "python".upper() "PYTHON"
.capitalize() Capitalizes first letter, lowercases remaining. "hello WORLD".capitalize() "Hello world"
.title() Capitalizes first letter of every word. "python data types".title() "Python Data Types"
.swapcase() Swaps uppercase to lower and vice versa. "PyThOn".swapcase() "pYtHoN"

2. Searching and Inspection Methods

  • .find(substring): Returns the lowest index where substring is found. Returns -1 if not found.
  • .index(substring): Same as .find(), but raises a ValueError if the substring is missing.
  • .count(substring): Returns the number of non-overlapping occurrences of substring.
  • .startswith(prefix): Returns True if the string starts with prefix.
  • .endswith(suffix): Returns True if the string ends with suffix.

3. Whitespace Cleaning and Replacement Methods

  • .strip(): Removes leading and trailing whitespace (or custom characters).
  • .lstrip() / .rstrip(): Removes whitespace from left or right side only.
  • .replace(old, new, [count]): Replaces occurrences of old with new. Optional count limits replacements.

4. Splitting and Joining Methods (Critical for Data Processing)

  • .split(sep): Splits a string into a list of substrings based on delimiter sep (defaults to whitespace).
  • .join(iterable): Joins elements of an iterable (e.g., list of strings) into a single string separated by the target delimiter string.
SPLIT_JOIN_DEMO.PY
# Data Cleaning & Processing Pipeline
raw_csv_row = "  python,java,javascript,cpp  "

# 1. Clean whitespace
cleaned_row = raw_csv_row.strip()

# 2. Split string into a list using comma delimiter
languages_list = cleaned_row.split(",")
print("Parsed List:", languages_list)

# 3. Join list items back into a formatted sentence
formatted_text = " | ".join(languages_list)
print("Joined Output:", formatted_text)
OUTPUT
Parsed List: ['python', 'java', 'javascript', 'cpp']
Joined Output: python | java | javascript | cpp

5. String Validation Methods (Predicate Checks)

Method Name Evaluates `True` If...
.isalpha() All characters are alphabetic letters (A-Z, a-z) and string is non-empty.
.isdigit() / .isnumeric() All characters are digits (0-9) and string is non-empty.
.isalnum() All characters are alphanumeric (letters or digits).
.isspace() String contains only whitespace characters (spaces, tabs, newlines).
.islower() / .isupper() All cased characters in string are lowercase / uppercase.

6. Membership Operators and String Concatenation

Membership Operators (`in` and `not in`)

Check efficiently whether a substring exists inside a target string, returning a Boolean:

text = "Artificial Intelligence & Data Science"
print("Data" in text)        # Outputs: True
print("Python" not in text)   # Outputs: True

String Operators (`+` and `*`)

  • Concatenation (`+`): Joins two or more strings together into a single string.
  • Repetition (`*`): Repeats a string a specified number of integer times.
STRING_OPERATORS.PY
header = "=" * 25
title = " SYSTEM STATUS "
full_banner = header + title + header

print(full_banner)
OUTPUT
========================= SYSTEM STATUS =========================

7. String Formatting Overview (Introduction)

Combining static text with dynamic variable values is a fundamental requirement in application development. Python has evolved through three primary string formatting mechanisms:

  1. % Formatting (Legacy C-Style): Uses %s, %d placeholders (e.g., "Hello %s" % name). Obsolete in modern Python.
  2. str.format() Method (Python 2.7+ / 3.0+): Uses curly brace placeholders (e.g., "Hello {}".format(name)).
  3. f-Strings (Formatted String Literals - Python 3.6+): Modern, clean, and fast formatting using f"Hello {name}" syntax.
Modern Standard: f-Strings are the preferred standard across the Python ecosystem due to superior performance and clean syntax readability. We will cover f-Strings and console I/O in complete detail in Lesson 9.

8. Frequently Asked Interview Questions with Answers

Q1: Why are strings immutable in Python, and what are the performance implications?
Answer: String immutability offers several technical advantages:
  • Security & Thread Safety: Strings used as dictionary keys, network addresses, or database URLs cannot be mutated unexpectedly by other threads.
  • String Interning: Python caches identical string literals in memory to save space and speed up equality comparisons.
  • Hashability: Immutability guarantees that a string's hash value remains constant throughout execution, allowing strings to serve as dictionary keys and set elements.
Q2: What is the difference between `.find()` and `.index()` methods?
Answer: Both locate the starting index of a substring. However, if the substring is not found, .find() returns -1 (making it safer for conditional checks), whereas .index() raises a ValueError exception.
Q3: How do you reverse a string in Python using slice notation?
Answer: Use the step parameter of -1 in slice notation: reversed_str = original_str[::-1]. This steps through the string from right to left, returning a reversed copy.
Q4: What is a Raw String in Python, and when should you use it?
Answer: A Raw String (created by prefixing a string with r, e.g., r"C:\dir\file") treats backslashes as literal characters rather than escape sequences. They are essential when defining regular expressions (Regex) or Windows file paths containing backslashes.
Q5: How do `.split()` and `.join()` complement each other in data processing pipelines?
Answer: .split(sep) breaks a single string into a list of substrings using delimiter sep. Conversely, delimiter.join(list) takes a list of strings and concatenates them into a single string separated by the delimiter.

9. Homework & Practical Assignment

Task 1: Email Domain Extractor Script

Create a script named email_parser.py inside your lesson_08 folder:

  • Define a variable email = " student.name@university.edu ".
  • Clean leading/trailing whitespace using .strip().
  • Extract the username (part before @) and domain (part after @) using .split("@") or slicing.
  • Print username and domain in uppercase.

Task 2: Palindrome Checker Script

Create a script named palindrome_checker.py:

  • Prompt the user or define a string variable (e.g., "Racecar").
  • Normalize the string by converting it to lowercase using .lower().
  • Reverse the string using slice notation ([::-1]).
  • Compare original normalized string with reversed string and print whether it is a valid Palindrome.

Task 3: Text Sanitizer and Word Counter

Write a script named text_sanitizer.py that takes raw text containing punctuation, replaces commas and periods with spaces using .replace(), splits text into words, and prints total word count using len().


10. File & Workspace Directory Structure

Standard Course Workspace Layout:

Ensure all exercise files are stored inside their corresponding lesson directories:

python_mastery_course/
│
├── lesson_01/
├── lesson_02/
├── lesson_03/
├── lesson_04/
├── lesson_05/
├── lesson_06/
├── lesson_07/
│
└── lesson_08/
    ├── raw_strings.py
    ├── string_immutability.py
    ├── string_slicing.py
    ├── split_join_demo.py
    ├── string_operators.py
    ├── email_parser.py
    ├── palindrome_checker.py
    └── text_sanitizer.py

11. What We Will Learn Next

Next Up: Lesson 9 — Input, Output and f-Strings

Now that you master string manipulation, slicing, and methods, we will explore advanced terminal console I/O and dynamic formatting.

In the next lesson, we will cover:

  • Terminal Input handling with input() and safe type conversion techniques.
  • Advanced Console Output with print() parameters (sep, end, flush).
  • Complete deep dive into f-Strings (Formatted String Literals): expressions, variable embedding, and evaluation.
  • Format Specifiers: Precision rounding (:.2f), alignment/padding (:>10, :<10, :^10), comma separators (:,), and percentage representations (:.1%).

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat