PART 2 โ€ข LEVEL 06

๐Ÿ”ค Strings

Create, inspect, transform and analyse text using precise indexing, slicing, methods, formatting and traversal techniques.

โฑ 90โ€“105 minutes๐Ÿ“š 8 concepts๐Ÿ’ป 5 programs๐Ÿง  6-question quiz
student_name.pyPython 3
raw_name = "  code bhavya  "
clean_name = raw_name.strip().title()
first_word = clean_name[:4]

print(f"Name: {clean_name}")
print(f"Prefix: {first_word}")
print(f"Length: {len(clean_name)}")
OUTPUTName: Code Bhavya
Prefix: Code
Length: 11

By the End of This Level

You will be able to process text safely and clearly.

01

Create strings and explain their immutable nature.

02

Access characters using positive and negative indexes.

03

Extract and reverse text using slicing.

04

Transform, search, format and traverse strings.

01

String Fundamentals and Immutability

A string is an ordered sequence of Unicode characters written inside matching quotes.

Single quotes, double quotes and triple quotes can create strings. Choose quotes that keep the content readable; triple quotes are useful for multi-line text.

Immutable

A string cannot be changed in place. Every apparent modification creates and returns a new string value.

Single quotes'Python'
Double quotes"CodeBhavya"
Empty string""
Lengthlen("Python") โ†’ 6
Immutability rule

word[0] = "J" raises an error. Build a new value instead, such as "J" + word[1:].

02

String Indexing

Indexing retrieves one character. Positive indexes begin at the left with 0; negative indexes begin at the right with โˆ’1.

ExpressionPositionResult for "Python"
word[0]First character'P'
word[2]Third character't'
word[-1]Last character'n'
word[-2]Second from the end'o'
EXAMPLE 1

Inspect Boundary Characters

course = "Python"
print("First:", course[0])
print("Last:", course[-1])
OUTPUT
First: P
Last: n
03

String Slicing

Slicing uses text[start:stop:step]. The start is included and the stop is excluded.

1Choose StartIncluded index
โ†’
2Choose StopExcluded index
โ†’
3Choose StepMovement amount
โ†’
4Build ResultNew string
SliceMeaningResult for "CodeBhavya"
text[0:4]Indexes 0 through 3Code
text[4:]Index 4 to the endBhavya
text[:4]Beginning through index 3Code
text[::2]Every second characterCdBaya
text[::-1]Reverse the sequenceayvahBedoC
04

String Operators and Membership

โž•

Concatenation

"Code" + "Bhavya" joins strings.

โœ–๏ธ

Repetition

"ha" * 3 produces hahaha.

๐Ÿ”

Membership

"Py" in "Python" is True.

โš–๏ธ

Comparison

Strings compare character by character using Unicode order.

EXAMPLE 2

Build and Search Text

brand = "Code" + "Bhavya"
has_code = "Code" in brand
print(brand)
print("Contains Code:", has_code)
OUTPUT
CodeBhavya
Contains Code: True
05

Essential String Methods

MethodPurposeExample result
strip()Remove outer whitespace" hi ".strip() โ†’ "hi"
lower() / upper()Change letter case"Py".lower() โ†’ "py"
title()Capitalize words"code bhavya".title()
replace()Replace occurrences"2025".replace("5", "6")
find()Return first index or โˆ’1"Python".find("th") โ†’ 2
count()Count occurrences"banana".count("a") โ†’ 3
startswith()Test the beginning"Python".startswith("Py")
isalpha()Test letters only"Code".isalpha()
Methods return values

Because strings are immutable, write clean = raw.strip(). Calling raw.strip() alone does not alter raw.

06

String Formatting

F-strings place expressions directly inside braces and are the clearest general choice for modern Python formatting.

EXAMPLE 3

Student Summary

name = "Bhavya"
score = 92.456
print(f"{name} scored {score:.2f}")
OUTPUT
Bhavya scored 92.46
METHOD

format()

"Name: {}".format(name)

Useful in older code and templates.

SIMPLE

Comma printing

print("Name:", name)

Convenient for basic labelled output.

07

String Traversal and Counting

A for loop can visit each character directly, making classification and counting problems easy to express.

EXAMPLE 4

Count Vowels

text = "Education"
vowels = 0

for character in text.lower():
    if character in "aeiou":
        vowels += 1

print("Vowels =", vowels)
OUTPUT
Vowels = 5

Common String Mistakes

Index Range
word[10]

An unavailable index raises IndexError; valid positive indexes stop at len(word) - 1.

Slice Stop
word[1:4]

The character at index 4 is excluded.

Immutability
word[0] = "J"

Create a new string instead of assigning to one character.

Method Result
name.strip()

Store or use the returned string; the original value remains unchanged.

Debug text processing:1. Display repr() when spaces matter2. Check length3. Mark indexes4. Verify slice boundaries5. Store method results
QUICK REVISION

๐Ÿ“Œ Strings โ€” Quick Revision

Review these rules before attempting the quiz and programming problems.

01

A string is an ordered, immutable character sequence.

02

Positive indexing starts at 0.

03

Negative indexing starts at โˆ’1 from the right.

04

A slice excludes its stop index.

05

[::-1] reverses a string.

06

+ joins strings and * repeats them.

07

in and not in test membership.

08

String methods return new values.

09

F-strings combine text and expressions clearly.

10

A for loop can visit every character directly.

Level 6 Quick Quiz

Select one answer for every question, then check your score.

6 Questions
1What is "Python"[-1]?
2What is "Python"[1:4]?
3Which expression reverses text?
4What does strip() remove by default?
5Which statement about strings is correct?
6What is "banana".count("a")?

PRACTICE

๐ŸŽฏ 5 Programming Problems โ€” Strings

Follow the CodeBhavya pattern: understand the task, inspect the sample, use the editor, run, check, then compare with the official program.

๐Ÿ“ˆ Strings Practice Progress
Solved0 / 5
Completed with Solution0
Total Score0 / 500
Completion0%

A problem counts as Solved when its output passes before the official solution is opened.

1. Clean Student Name

Remove outer spaces and convert the supplied name to title case.

Sample input: code bhavya Expected output: Clean = Code Bhavya
2. Character at an Index

Read text and an index, then display the character at that index.

Sample input: Python, 2Expected output: Character = t
3. Extract the Brand Name

Read text, start and stop indexes, then display the requested slice.

Sample input: CodeBhavya, 4, 10Expected output: Slice = Bhavya
4. Reverse Text

Read a string and display it in reverse order using slicing.

Sample input: CodeBhavyaExpected output: Reversed = ayvahBedoC
5. Count Vowels

Read text and count its vowels without treating uppercase and lowercase differently.

Sample input: EducationExpected output: Vowels = 5
KEY TAKEAWAY

๐ŸŽฏ Treat Text as an Ordered Sequence

1Normalize

Clean spaces and letter case.

โ†’
2Locate

Use indexes and slices precisely.

โ†’
3Transform

Store method results as new strings.

โ†’
4Analyse

Traverse and count characters.

Reliable text processing starts by understanding that strings are ordered and immutable: inspect precisely, transform into new values and verify boundaries.

INTERACTIVE LEARNING

๐ŸŽฌ String Slicing โ€” Visual Flow

Watch Python evaluate "Python"[1:5:2] from its start, stop and step values.

PROGRAM TRACING

๐Ÿ”Ž Program Tracing โ€” Vowel Counter

Trace each character in Code and observe how the vowel counter changes.

INTERVIEW PREPARATION

๐ŸŽค Strings โ€” Interview Questions

Answer aloud before opening each explanation.

1.

Why are Python strings called immutable?

2.

What is the difference between indexing and slicing?

3.

Why is the stop index excluded from a slice?

4.

What does find() return when text is absent?

5.

How do isalpha() and isalnum() differ?

6.

What is the time complexity of scanning every character once?

EXTRA TIPS

๐Ÿ’ก Strings โ€” Extra Tips

  • 01

    Normalize user input with strip() before validation or comparison.

  • 02

    Use casefold() for robust case-insensitive international text comparison.

  • 03

    Prefer in when you only need to know whether a substring exists.

  • 04

    Use join() for efficiently combining many string pieces.

  • 05

    Remember that a space is a character and contributes to len().

  • 06

    When debugging hidden whitespace, inspect the value with repr().

EXTRA PRACTICE

โœ๏ธ Strings โ€” Extra Practice Questions

  1. Check whether a supplied word is a palindrome.
  2. Count uppercase letters, lowercase letters, digits and spaces separately.
  3. Remove every space from a sentence without using replace().
  4. Find the first and last positions of a supplied character.
  5. Count how many times each vowel occurs.
  6. Replace repeated spaces with a single space.
  7. Display every word of a sentence on a separate line.
  8. Create initials from a full name.
  9. Check whether two strings are anagrams after normalizing case and spaces.
  10. Perform run-length encoding for consecutive repeated characters.

Strings Complete

When you can trace indexes, design slices, select suitable methods and solve all five programs without help, mark this level complete and continue.