Create strings and explain their immutable nature.
๐ค Strings
Create, inspect, transform and analyse text using precise indexing, slicing, methods, formatting and traversal techniques.
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)}")Prefix: Code
Length: 11
By the End of This Level
You will be able to process text safely and clearly.
Access characters using positive and negative indexes.
Extract and reverse text using slicing.
Transform, search, format and traverse strings.
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.
A string cannot be changed in place. Every apparent modification creates and returns a new string value.
'Python'"CodeBhavya"""len("Python") โ 6word[0] = "J" raises an error. Build a new value instead, such as "J" + word[1:].
String Indexing
Indexing retrieves one character. Positive indexes begin at the left with 0; negative indexes begin at the right with โ1.
| Expression | Position | Result for "Python" |
|---|---|---|
word[0] | First character | 'P' |
word[2] | Third character | 't' |
word[-1] | Last character | 'n' |
word[-2] | Second from the end | 'o' |
Inspect Boundary Characters
course = "Python"
print("First:", course[0])
print("Last:", course[-1])First: P Last: n
String Slicing
Slicing uses text[start:stop:step]. The start is included and the stop is excluded.
| Slice | Meaning | Result for "CodeBhavya" |
|---|---|---|
text[0:4] | Indexes 0 through 3 | Code |
text[4:] | Index 4 to the end | Bhavya |
text[:4] | Beginning through index 3 | Code |
text[::2] | Every second character | CdBaya |
text[::-1] | Reverse the sequence | ayvahBedoC |
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.
Build and Search Text
brand = "Code" + "Bhavya"
has_code = "Code" in brand
print(brand)
print("Contains Code:", has_code)CodeBhavya Contains Code: True
Essential String Methods
| Method | Purpose | Example 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() |
Because strings are immutable, write clean = raw.strip(). Calling raw.strip() alone does not alter raw.
String Formatting
F-strings place expressions directly inside braces and are the clearest general choice for modern Python formatting.
Student Summary
name = "Bhavya"
score = 92.456
print(f"{name} scored {score:.2f}")Bhavya scored 92.46
F-string
f"Name: {name}"Readable and supports expressions.
format()
"Name: {}".format(name)Useful in older code and templates.
Comma printing
print("Name:", name)Convenient for basic labelled output.
String Traversal and Counting
A for loop can visit each character directly, making classification and counting problems easy to express.
Count Vowels
text = "Education"
vowels = 0
for character in text.lower():
if character in "aeiou":
vowels += 1
print("Vowels =", vowels)Vowels = 5
Common String Mistakes
word[10]An unavailable index raises IndexError; valid positive indexes stop at len(word) - 1.
word[1:4]The character at index 4 is excluded.
word[0] = "J"Create a new string instead of assigning to one character.
name.strip()Store or use the returned string; the original value remains unchanged.
repr() when spaces matter2. Check length3. Mark indexes4. Verify slice boundaries5. Store method results๐ Strings โ Quick Revision
Review these rules before attempting the quiz and programming problems.
A string is an ordered, immutable character sequence.
Positive indexing starts at 0.
Negative indexing starts at โ1 from the right.
A slice excludes its stop index.
[::-1] reverses a string.
+ joins strings and * repeats them.
in and not in test membership.
String methods return new values.
F-strings combine text and expressions clearly.
A for loop can visit every character directly.
Level 6 Quick Quiz
Select one answer for every question, then check your score.
๐ฏ 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.
A problem counts as Solved when its output passes before the official solution is opened.
Remove outer spaces and convert the supplied name to title case.
code bhavya Expected output: Clean = Code Bhavyastrip() and title().Python Code Editor
Program Output
Run your program to see the output.
Test Case
name = input()
clean = name.strip().title()
print("Clean =", clean)Read text and an index, then display the character at that index.
Python, 2Expected output: Character = tPython Code Editor
Program Output
Run your program to see the output.
Test Case
text = input()
index = int(input())
character = text[index]
print("Character =", character)Read text, start and stop indexes, then display the requested slice.
CodeBhavya, 4, 10Expected output: Slice = Bhavyatext[start:stop]; the stop index is excluded.Python Code Editor
Program Output
Run your program to see the output.
Test Case
text = input()
start = int(input())
stop = int(input())
part = text[start:stop]
print("Slice =", part)Read a string and display it in reverse order using slicing.
CodeBhavyaExpected output: Reversed = ayvahBedoC-1 visits characters from right to left.Python Code Editor
Program Output
Run your program to see the output.
Test Case
text = input()
reversed_text = text[::-1]
print("Reversed =", reversed_text)Read text and count its vowels without treating uppercase and lowercase differently.
EducationExpected output: Vowels = 5"aeiou".Python Code Editor
Program Output
Run your program to see the output.
Test Case
text = input()
vowels = 0
for character in text.lower():
if character in "aeiou":
vowels += 1
print("Vowels =", vowels)๐ฏ Treat Text as an Ordered Sequence
Clean spaces and letter case.
Use indexes and slices precisely.
Store method results as new strings.
Traverse and count characters.
๐ฌ String Slicing โ Visual Flow
Watch Python evaluate "Python"[1:5:2] from its start, stop and step values.
โ๏ธ How Python Builds a String Slice
1. Read the Indexed Sequence
Python maps the characters in Python to indexes 0 through 5.
๐ Program Tracing โ Vowel Counter
Trace each character in Code and observe how the vowel counter changes.
Click Next to begin tracing.
โ
๐ค Strings โ Interview Questions
Answer aloud before opening each explanation.
Why are Python strings called immutable?
The characters of an existing string cannot be changed in place. String operations create new string objects.
What is the difference between indexing and slicing?
Indexing retrieves one character and may raise IndexError. Slicing produces a new substring and safely clips out-of-range boundaries.
Why is the stop index excluded from a slice?
The half-open design makes slice length predictable as stop - start when the step is 1 and makes adjacent slices fit without overlap.
What does find() return when text is absent?
find() returns -1. By contrast, index() raises ValueError when the substring is absent.
How do isalpha() and isalnum() differ?
isalpha() requires letters only. isalnum() accepts letters and digits, with at least one character present.
What is the time complexity of scanning every character once?
For a string of length n, a single full traversal takes linear time: O(n).
๐ก 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
inwhen 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().
โ๏ธ Strings โ Extra Practice Questions
- Check whether a supplied word is a palindrome.
- Count uppercase letters, lowercase letters, digits and spaces separately.
- Remove every space from a sentence without using
replace(). - Find the first and last positions of a supplied character.
- Count how many times each vowel occurs.
- Replace repeated spaces with a single space.
- Display every word of a sentence on a separate line.
- Create initials from a full name.
- Check whether two strings are anagrams after normalizing case and spaces.
- 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.
