Learn • Experiment • Solve • Build
“A string is more than a collection of characters—it is a message waiting to be explored!”
๐ Welcome to the World of Strings!
Imagine you receive this message:
Hello Sukhbir! Welcome to Python.
Computers don't see this as a sentence. Python sees it as a string—a sequence of characters.
A string can contain:
Letters
Numbers
Spaces
Symbols
Special characters
For example:
name = "Raman"
city = "Noida"
message = "Python is Fun!"
All three variables contain strings.
1. Creating a String
Strings can be created using:
Single quotes
name = 'Raman'
Double quotes
name = "Raman"
Both are perfectly valid.
name1 = 'Python'
name2 = "Python"
print(name1)
print(name2)
Output
Python
Python
2. Strings Are a Sequence
Here's an important idea:
word = "PYTHON"
Python stores the characters in a sequence:
P Y T H O N
↓ ↓ ↓ ↓ ↓ ↓
0 1 2 3 4 5
Each character has a position called an index.
Python starts counting from 0, not 1.
3. String Indexing ๐
Indexing means accessing an individual character from a string.
word = "PYTHON"
print(word[0])
print(word[1])
print(word[5])
Output
P
Y
N
Remember:
P Y T H O N
0 1 2 3 4 5
๐ง Python Pebble
Index = Position of a character
The first character always has index 0.
4. Negative Indexing
Python also allows us to count from the end.
P Y T H O N
-6 -5 -4 -3 -2 -1
Example:
word = "PYTHON"
print(word[-1])
print(word[-2])
Output
N
O
So:
word[-1]
means:
Give me the last character.
5. String Slicing ✂️
What if we want more than one character?
That's where slicing comes in.
Syntax:
string[start:end]
The start position is included, but the end position is excluded.
word = "PYTHON"
print(word[0:3])
Output
PYT
Why?
P Y T H O N
0 1 2 3 4 5
|---|
0 1 2
The character at index 3 is not included.
More Slicing Examples
word = "PYTHON"
print(word[1:4])
print(word[2:6])
print(word[:3])
print(word[3:])
Output
YTH
THON
PYT
HON
6. Slicing with a Step
We can also specify a step.
word = "PYTHON"
print(word[0:6:2])
Output
PTO
It selects:
P → T → O
Syntax:
string[start:end:step]
7. Reverse a String ๐
Here's one of Python's most useful string tricks:
word = "PYTHON"
print(word[::-1])
Output
NOHTYP
The -1 step means:
Move backwards one character at a time.
8. Finding the Length – len()
How many characters are present in a string?
Use len().
name = "Raman"
print(len(name))
Output
5
Spaces are also counted.
message = "Hello World"
print(len(message))
Output
11
Why 11?
Hello = 5
Space = 1
World = 5
Total = 11
9. Changing Case
Python provides useful methods for changing the case of characters.
upper()
name = "python"
print(name.upper())
Output:
PYTHON
lower()
name = "PYTHON"
print(name.lower())
Output:
python
Real-Life Example
Suppose a student enters:
raman
We can convert it to:
name = "raman"
print(name.upper())
Output:
RAMAN
10. Removing Extra Spaces – strip()
Sometimes users accidentally enter spaces.
name = " Raman "
print(name.strip())
Output:
Raman
strip() removes spaces from the beginning and end.
Important
It does not remove spaces between words.
message = "Hello World"
print(message.strip())
Output:
Hello World
11. Replacing Text – replace()
Suppose we want to replace one word with another.
message = "I like Java"
message = message.replace("Java", "Python")
print(message)
Output:
I like Python
Another Example
text = "cat cat cat"
print(text.replace("cat", "dog"))
Output:
dog dog dog
12. Splitting a String – split()
Suppose we have:
data = "Python is easy"
We can split it into individual words.
words = data.split()
print(words)
Output:
['Python', 'is', 'easy']
The result is a list.
Splitting Using a Separator
data = "apple,banana,mango"
fruits = data.split(",")
print(fruits)
Output:
['apple', 'banana', 'mango']
๐ง Remember
split():
String → List
13. Joining Strings – join()
Now let's go in the opposite direction.
Suppose:
words = ["Python", "is", "fun"]
We want:
Python is fun
Use join().
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)
Output:
Python is fun
Another Example
words = ["2026", "10", "05"]
date = "-".join(words)
print(date)
Output:
2026-10-05
๐ง Python Pebble
split()breaks a string apart.join()puts strings together.
14. Searching Inside a String – find()
Want to know where a word occurs?
Use find().
message = "Python is powerful"
print(message.find("powerful"))
Output:
10
Why?
Python is powerful
0123456789...
If the text is not found:
message = "Python is powerful"
print(message.find("Java"))
Output:
-1
So -1 means:
The searched text was not found.
15. Counting Characters – count()
How many times does a character occur?
word = "banana"
print(word.count("a"))
Output:
3
We can also count words or groups of characters.
message = "Python is easy. Python is powerful."
print(message.count("Python"))
Output:
2
16. Checking the Beginning – startswith()
We can check whether a string starts with particular text.
website = "pythonpebbles"
print(website.startswith("python"))
Output:
True
Another example:
name = "Raman"
print(name.startswith("Ram"))
print(name.startswith("Raj"))
Output:
True
False
17. Checking the Ending – endswith()
Similarly, we can check how a string ends.
filename = "student.py"
print(filename.endswith(".py"))
Output:
True
This can be useful when checking file types.
filename = "photo.jpg"
print(filename.endswith(".py"))
Output:
False
18. f-Strings – The Smart Way to Create Messages ๐
Suppose we have:
name = "Raman"
marks = 92
We want:
Raman scored 92 marks.
We can use an f-string.
name = "Raman"
marks = 92
print(f"{name} scored {marks} marks.")
Output:
Raman scored 92 marks.
The f tells Python:
“I want to insert variables inside this string.”
Multiple Variables
name = "Raman"
age = 14
city = "Noida"
print(f"{name} is {age} years old and lives in {city}.")
Output:
Raman is 14 years old and lives in Noida.
19. Calculations Inside f-Strings
We can even perform calculations.
price = 500
quantity = 3
print(f"Total amount = ₹{price * quantity}")
Output:
Total amount = ₹1500
That's powerful!
20. Formatting Numbers
Suppose:
price = 1234.5678
We want only two decimal places.
print(f"{price:.2f}")
Output:
1234.57
Percentage Example
score = 92.4567
print(f"Score: {score:.2f}%")
Output:
Score: 92.46%
21. Traditional String Formatting
Python also supports other formatting techniques.
.format()
name = "Raman"
marks = 95
print("{} scored {} marks.".format(name, marks))
Output:
Raman scored 95 marks.
We can also use positions:
print("{0} scored {1} marks.".format(name, marks))
For modern Python programs, f-strings are generally easier to read.
22. Escape Characters ๐
What happens if we want to print:
He said, "Python is fun!"
We can use escape characters.
print("He said, \"Python is fun!\"")
Output:
He said, "Python is fun!"
The backslash \ tells Python that the following character has a special meaning.
Common Escape Characters
| Escape | Meaning |
|---|---|
\n | New line |
\t | Tab |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
New Line
print("Hello\nPython")
Output:
Hello
Python
Tab
print("Name\tMarks")
print("Raman\t95")
Output:
Name Marks
Raman 95
23. Multi-Line Strings
Triple quotes can be used for multiple lines.
message = """Welcome to Python Pebbles!
Learn Python.
Practice Python.
Build Python projects.
"""
print(message)
Output:
Welcome to Python Pebbles!
Learn Python.
Practice Python.
Build Python projects.
24. Strings Are Immutable ๐
Here's a very important Python concept.
You cannot directly change an individual character of a string.
This will produce an error:
word = "Python"
word[0] = "J"
Strings are immutable.
Instead, create a new string.
word = "Python"
word = "J" + word[1:]
print(word)
Output:
Jython
๐ง Python Pebble
Immutable means the original string cannot be changed character-by-character.
25. The Palindrome Challenge ๐
A palindrome reads the same forward and backward.
Examples:
MADAM
LEVEL
RADAR
121
Let's check one.
word = "madam"
if word == word[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
Output:
Palindrome
๐ฏ User Input Palindrome
word = input("Enter a word: ")
if word == word[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
Try:
Enter a word: level
Palindrome
26. Palindrome – Advanced Version
What if the user enters:
Madam
The comparison becomes:
Madam
madam
We can normalize the input.
word = input("Enter a word: ")
word = word.lower()
if word == word[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
27. Anagram Challenge ๐
Two words are anagrams if they contain the same letters in a different order.
Examples:
listen
silent
Both contain:
l, i, s, t, e, n
We can solve this using sorted().
word1 = "listen"
word2 = "silent"
if sorted(word1) == sorted(word2):
print("Anagram")
else:
print("Not an Anagram")
Output:
Anagram
Why Does It Work?
sorted("listen")
produces characters in sorted order:
['e', 'i', 'l', 'n', 's', 't']
And:
sorted("silent")
produces the same result.
Therefore, they are anagrams.
28. Making Anagram Checking User-Friendly
Users may enter uppercase and lowercase letters.
word1 = input("Enter first word: ")
word2 = input("Enter second word: ")
word1 = word1.lower()
word2 = word2.lower()
if sorted(word1) == sorted(word2):
print("Anagram")
else:
print("Not an Anagram")
29. Frequency Counting ๐
Suppose we have:
word = "banana"
We want to know:
b → 1
a → 3
n → 2
One simple method is using count().
word = "banana"
for ch in "ban":
print(ch, word.count(ch))
Output:
b 1
a 3
n 2
But what if we don't know which characters exist?
That's where a dictionary becomes extremely useful.
30. Character Frequency Using a Dictionary
word = "banana"
frequency = {}
for ch in word:
if ch in frequency:
frequency[ch] += 1
else:
frequency[ch] = 1
print(frequency)
Output:
{'b': 1, 'a': 3, 'n': 2}
How does it work?
First:
b → 1
Then:
a → 1
Then:
n → 1
When a appears again:
a → 2
And again:
a → 3
31. Frequency Counting – Using get()
We can make the program shorter.
word = "banana"
frequency = {}
for ch in word:
frequency[ch] = frequency.get(ch, 0) + 1
print(frequency)
Output:
{'b': 1, 'a': 3, 'n': 2}
This is an important programming pattern.
Count = previous count + 1
32. Word Frequency
Frequency counting isn't limited to characters.
Consider:
sentence = "python is easy and python is powerful"
We can count words.
words = sentence.split()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
print(frequency)
Output:
{'python': 2, 'is': 2, 'easy': 1, 'and': 1, 'powerful': 1}
Now our program is becoming a small text-analysis tool!
33. A Mini Text Analyzer ๐
Let's combine several string concepts.
text = input("Enter a sentence: ")
print("\n--- Text Analysis ---")
print("Characters:", len(text))
print("Uppercase:", text.upper())
print("Lowercase:", text.lower())
words = text.split()
print("Number of words:", len(words))
Example:
Enter a sentence: Python is easy to learn
Output:
--- Text Analysis ---
Characters: 24
Uppercase: PYTHON IS EASY TO LEARN
Lowercase: python is easy to learn
Number of words: 5
34. Mini Project – Student Name Formatter ๐
Suppose a student enters:
rAMAN sINGH
We want:
Raman Singh
One approach:
name = input("Enter your name: ")
name = name.strip()
name = name.lower()
name = name.title()
print(f"Welcome, {name}!")
Output:
Enter your name: rAMAN sINGH
Welcome, Raman Singh!
Here we combined:
input()strip()lower()title()f-strings
35. Mini Project – Username Validator ๐
Let's check whether a username:
starts with
"ram"ends with a number
has at least 5 characters
username = input("Enter username: ")
if len(username) >= 5 and username.startswith("ram"):
print("Username format looks good.")
else:
print("Invalid username.")
This introduces an important idea:
String methods can be combined with conditions to solve real-world problems.
36. Mini Project – Word Search ๐
sentence = input("Enter a sentence: ")
word = input("Enter word to search: ")
position = sentence.lower().find(word.lower())
if position != -1:
print(f"Word found at position {position}")
else:
print("Word not found.")
Example:
Enter a sentence: Python is easy to learn
Enter word to search: easy
Output:
Word found at position 10
๐ง Python Pebble Challenge 1 – Predict the Output
What will this program print?
word = "PYTHON"
print(word[1:5])
print(word[-3:])
print(word[::-1])
Think before running the program!
๐ง Python Pebble Challenge 2 – Find the Bug
What is wrong with this program?
name = "Python"
name[0] = "J"
print(name)
Hint
Think about immutability.
๐ง Python Pebble Challenge 3 – Palindrome
Write a program that accepts a word and determines whether it is a palindrome.
Example:
Enter word: radar
Palindrome
๐ง Python Pebble Challenge 4 – Anagram
Write a program that accepts two words and checks whether they are anagrams.
Example:
First word: triangle
Second word: integral
Anagram
๐ง Python Pebble Challenge 5 – Character Counter
Write a program that accepts a string and displays the frequency of every character.
Example:
Enter text: hello
Expected result:
h : 1
e : 1
l : 2
o : 1
๐ Python Pebbles – Master Challenge
Create a Text Analyzer that accepts a sentence and displays:
Number of characters
Number of words
Uppercase version
Lowercase version
First character
Last character
Number of occurrences of
"Python"Whether the sentence starts with
"Python"Whether it ends with
"."Frequency of every character
Sample Input
Python is easy. Python is powerful.
Your program should produce a report similar to:
------ TEXT ANALYZER ------
Characters : 35
Words : 6
Uppercase:
PYTHON IS EASY. PYTHON IS POWERFUL.
Lowercase:
python is easy. python is powerful.
First Character : P
Last Character : .
Python Count : 2
Starts with Python : True
Ends with . : True
Character Frequency:
P : 2
y : 2
t : 2
h : 2
o : ...
๐ Quick Revision – String Toolkit
| Function / Method | Purpose |
|---|---|
len() | Finds string length |
upper() | Converts to uppercase |
lower() | Converts to lowercase |
strip() | Removes leading/trailing whitespace |
replace() | Replaces text |
split() | Converts string into a list |
join() | Joins strings |
find() | Finds position of text |
count() | Counts occurrences |
startswith() | Checks beginning |
endswith() | Checks ending |
[::-1] | Reverses a string |
f"" | Creates formatted strings |
format() | Formats strings |
\n | New line |
\t | Tab |
๐ What Have We Learned?
We started with:
"Hello"
But now we can:
๐ Explore characters
✂️ Slice strings
๐ Reverse strings
๐ Search text
๐ Count characters
๐งน Clean user input
๐ Split and join data
๐จ Format output
๐ Work with escape characters
๐ง Detect palindromes
๐ Detect anagrams
๐ Calculate frequencies
๐ Build text-analysis programs
That's the real power of Python strings.
๐ชจ One Final Python Pebble
Remember these five ideas:
1️⃣ Indexing
word[0]
Get one character.
2️⃣ Slicing
word[1:4]
Get part of a string.
3️⃣ Methods
word.upper()
Process the string.
4️⃣ Formatting
f"Hello {name}"
Build useful messages.
5️⃣ Problem Solving
word == word[::-1]
Use strings to solve real problems.
Don't just memorize string methods. Experiment with them, combine them, and use them to build something!
๐ฏ Practice Mission
Before moving to the next Python Pebble, try building these five programs:
Name Formatter
Palindrome Checker
Anagram Checker
Character Frequency Counter
Complete Text Analyzer
Once you can build these without looking at the solution, you've moved from learning strings to thinking like a Python programmer.
No comments:
Post a Comment