Chapter 03 of 13

Working
with Strings

Master the power of text manipulation in Python. Learn string slicing, negative indexing, immutability, built-in string methods, and f-strings to build real-world text-processing applications.

~55 min read
Beginner Level
5 Exercises
strings.py — Python Mastery
1# Chapter 3 — Working with Strings
2name = "Harsh"
3message = f"Welcome {name}!"
4
5print(message[0:7]) # Slicing
6print(name.upper()) # Method
String Slicing
f-strings
Creating Strings
Single, double, triple quotes
String Indexing
0-based & Negative Indexing
Slicing
string[start:end:skip]
Immutability
Strings cannot be changed in place
String Methods
len, count, replace, find etc.
Escape Sequences
\n, \t, escape characters
Real Use Cases
Validations, input, AI chatbots
Practice Set
Solve 5 practice problems

What is a String?

Strings are one of the most commonly used data types in Python. Whenever we work with text such as names, messages, emails, passwords, addresses, or user input, we use strings.

A string is simply a sequence of characters enclosed within quotes. Strings allow us to store, display, modify, and manipulate textual data easily.

Syntax Rule
Python provides multiple ways to create strings: single quotes, double quotes, and triple quotes.
string_creation.py
1name = "Harsh"
2city = "Lucknow"
3message = "Welcome to Python Mastery with Harsh"

Quotation Styles in Python

You can define strings using single, double, or triple quotes. Choose the one that suits your needs.

Single Quotes

Use for short strings where you don't need double quote escaping.

single.py
1name = 'Harsh'
Double Quotes

The standard style for most Python developers.

double.py
1name = "Harsh"
Triple Quotes

Perfect for writing multi-line text or preserving line breaks.

triple.py
1message = '''Welcome to
2Python Mastery
3with Harsh'''

String Indexing

Every character in a string occupies a position number called an index. Python starts counting indices from 0.

H a r s h 0 1 2 3 4 INDEX: -5 -4 -3 -2 -1 NEGATIVE:

To access a specific character, write the variable name followed by the index enclosed in square brackets `[]`.

indexing.py
1name = "Harsh"
2
3print(name[0]) # First character
4print(name[1]) # Second character
5print(name[-1]) # Last character
Terminal Output
H
a
h

String Slicing

Slicing allows us to extract a portion of a string. We specify where to start and where to end.

Slicing Syntax
Syntax Template
`string[start : end]` — Python slices from the `start` index and stops *before* the `end` index (non-inclusive of the end index).

If you omit the start, it defaults to `0`. If you omit the end, it defaults to the length of the string.

Slicing with a Skip Value
Skip Syntax
`string[start : end : skip]` — Python extracts characters at the step interval defined by `skip`.
slicing.py
1word = "Programming"
2print(word[0:7]) # Output: Program
3
4word2 = "Amazing"
5print(word2[1:6:2]) # Starts index 1, skips every 2nd → mzn
6
7print(word2[:7]) # Defaults start to 0 → Amazing
8print(word2[0:]) # Defaults end to end of string → Amazing
9print(word2[:]) # Full slice copy → Amazing
Terminal Output
Program
mzn
Amazing
Amazing
Amazing

String Immutability

Once a string is created in memory, its individual characters cannot be changed or modified in place.

Why does this fail?
In Python, strings are **immutable**. Attempting to modify an index (e.g. `name[0] = 'M'`) will raise a `TypeError`.

If you want to modify a string, you must create a new string variable with the desired change. Python does this to optimize memory and run faster.

immutability.py
1name = "Harsh"
2# name[0] = "M" <-- This raises TypeError!
3
4# Correct way is creating a new reference:
5name = "Marsh"
6print(name)
Terminal Output
Marsh

String Functions & Methods

Python provides powerful built-in functions and object methods to analyze, validate, and manipulate text strings.

Common String Operations
  • len(str): Returns the total number of characters in the string.
  • str.endswith(val): Returns `True` if the string ends with the specified suffix value.
  • str.count(val): Counts how many times a substring appears in the string.
  • str.capitalize(): Capitalizes the very first letter of the string.
  • str.find(val): Searches for a substring and returns its index. Returns `-1` if not found.
  • str.replace(old, new): Replaces occurrences of `old` text with `new` text.
Casing & Formatting
  • str.upper(): Converts all characters to uppercase.
  • str.lower(): Converts all characters to lowercase.
  • str.strip(): Trims white space from both the start and end of a string.
string_methods.py
1text = "harsh"
2print(len(text)) # Length: 5
3print(text.endswith("sh")) # True
4print(text.count("h")) # 2 ('h' occurs twice)
5print(text.capitalize()) # Harsh
6print(text.find("rs")) # 2
7print(text.replace("h", "m")) # marsm
8
9print("python".upper()) # PYTHON
10print("PYTHON".lower()) # python
11print(" Python ".strip()) # Python (trims spaces)
Terminal Output
5
True
2
Harsh
2
marsm
PYTHON
python
Python

Escape Sequences

Escape sequences start with a backslash `\` and are used to include characters that are otherwise hard or impossible to write inside strings.

Common Escape Codes
  • `\n` : Adds a **New Line** break.
  • `\t` : Inserts a horizontal **Tab Space**.
  • `\"` : Includes a **Double Quote** inside double-quoted text.
  • `\'` : Includes a **Single Quote** inside single-quoted text.
escape.py
1print("Hello\nWorld")
2print("Python\tCourse")
3print("Harsh said \"Python is awesome\"")
4print('It\'s a beautiful day')
Terminal Output
Hello
World
Python Course
Harsh said "Python is awesome"
It's a beautiful day

Where Strings are Used

Almost every Python application deals with string data. Here are the primary domains:

Users & Passwords

Authenticating usernames, matching encrypted password hashes, and processing logins.

Email Processing

Formatting and validating emails, scanning messages for spam, and routing alerts.

AI Chatbots

Parsing human questions, generating text responses, and feeding text into models.

Search Engines

Analyzing web text queries, matching strings using indexing, and ranking results.

Python Strings – Interview Questions

A string in Python is a sequence of characters enclosed within single quotes ('...'), double quotes ("..."), or triple quotes ('''...''' or """..."""). It is an immutable data type, meaning once a string is created, its individual characters cannot be modified or replaced.

String Indexing is used to access a single character at a specific position by referencing its index position (e.g. name[0]). String Slicing is used to extract a range of characters (a substring) using the start and end index boundaries (e.g. name[1:4]). Slicing doesn't raise an error even if indices are out of range.

String immutability means that a string's characters cannot be updated or changed in-place after the string has been created. For example, doing word[0] = 'P' will raise a TypeError. If you need a modified string, you must create a new string variable. This ensures memory efficiency and security.

The find(sub) method searches for a substring and returns the lowest index where it begins (or returns -1 if it is not found). The replace(old, new) method returns a new string where all occurrences of the old substring are replaced by the new substring. Neither method alters the original string.

Escape sequence characters are special combinations of characters consisting of a backslash (\) followed by a letter or symbol. They are used to format text in ways that are otherwise hard to express directly. Common escape sequences include \n for newline, \t for a horizontal tab space, and \" or \' to insert literal quotes inside single or double-quoted strings.

Some of the most common string functions and methods include: len() (gets string length), endswith(suffix) (checks suffix), count(substring) (counts occurrences), capitalize() (capitalizes the first character), upper() / lower() (case conversion), and strip() (removes leading/trailing whitespace).

Practice Questions

Write every line yourself — the best way to learn is by doing, not just reading.

Q1Easy
Good Afternoon Program

Write a Python program to display a user-entered name followed by "Good Afternoon" using the input() function.

Hint: Use input() to get the name, and print using an f-string: f"Good Afternoon, {name}".
Q2Easy
Letter Template Replacer

Write a program to fill in a letter template dynamically, replacing <|Name|> and <|Date|> placeholders with actual inputs.

Hint: Use a multiline string template, then chain .replace("<|Name|>", name).replace("<|Date|>", date).
Q3Easy
Detect Double Spaces

Write a Python program to detect double spaces (e.g. " ") inside a target string.

Hint: Use the .find(" ") method. A return value other than -1 indicates double spaces exist.
Q4Medium
Replace Double Spaces

Modify the program from Question 3 to replace all double spaces in a string with a single space.

Hint: Use the .replace(" ", " ") method. Note that because strings are immutable, this returns a new string.
Q5Medium
Format Letter via Escape Codes

Format the following letter using escape sequence characters for clean readability: "Dear Harsh, this Python course is amazing. Thanks!"

Hint: Format using newline \n and tab \t escape characters inside a single string.

Chapter Summary

Strings are sequences of characters enclosed inside single ('...'), double ("..."), or triple ('''...''') quotes.
String Indexing starts at 0 for the first character, while Negative Indexing starts at -1 from the right side.
String Slicing extracts a portion of a string using string[start:end] (non-inclusive of the end index).
Slicing with step syntax string[start:end:skip] retrieves characters by stepping over the interval defined by skip.
Strings in Python are immutable, meaning you cannot change individual characters in-place once created.
Built-in string functions include len(), capitalize(), endswith(), count(), find(), and replace().
Case conversions can be done using .upper(), .lower(), and leading/trailing whitespace can be trimmed with .strip().
Escape Sequence Characters (like \n for newline, \t for tab) let you include special characters inside text.
Completion Checklist
Understand Strings & Quotation Styles
Use Indexing & Negative Indexing
Perform String Slicing with Skip Value
Understand String Immutability Rules
Use String Built-in Methods & Functions
Understand Escape Sequence Characters
Solve All Practice Questions
Your Progress
0/7
Excellent Work!

You have successfully completed Chapter 3 — Strings. You can now process, clean, and format textual data in Python!

Chapter 3 Complete!

Three chapters down, ten to go. You're building serious Python foundations — keep the momentum!

23.1%
3 of 13 chapters completed
Back to Course Home
Ch 1
Modules
Ch 2
Variables
Ch 3
Strings
4
Ch 4
Lists
5
Ch 5
Loops
...
More
Coming