Accessing Characters and Substrings in Strings (Python)
1. Accessing Characters in a String
• In Python, a string is a sequence of characters.
• Each character has an index number.
• Index starts from 0 (first character).
• Negative index starts from the end.
Example (Python code):
s = "PYTHON"
print(s[0]) # P (first character)
print(s[3]) # H (fourth character)
print(s[-1]) # N (last character)
print(s[-2]) # O (second last)
2. Accessing Substrings (Slicing)
• Substring = a part of the string.
• Syntax: s[start:end] → includes characters from start to end-1.
• If start is empty → begins from 0.
• If end is empty → goes till last character.
Example (Python code):
s = "PYTHON"
print(s[0:3]) # PYT (index 0 to 2)
print(s[2:5]) # THO (index 2 to 4)
print(s[:4]) # PYTH (from start to index 3)
print(s[2:]) # THON (from index 2 to end)
3. Step Value in Slicing
• Syntax: s[start:end:step]
• Step = number of characters to skip.
• Step = -1 → reverses the string.
Example (Python code):
s = "PYTHON"
print(s[::2]) # PYO (every 2nd character)
print(s[::-1]) # NOHTYP (reverse string)
Python – Strings, Number Systems, String Methods, and File Handling
1. Data Encryption with Strings
• Encryption = converting normal text into secret code.
• In Python, we can encrypt a string by changing each character into another form (for
example shifting ASCII values).
Example:
msg = "HELLO"
encrypted = ""
for ch in msg:
encrypted += chr(ord(ch) + 1) # shift by +1
print("Encrypted:", encrypted) # IFMMP
Here, "HELLO" becomes "IFMMP".
2. Strings and Number Systems
Python can easily convert numbers between different number systems.
• Binary (base 2) → bin()
• Octal (base 8) → oct()
• Hexadecimal (base 16) → hex()
Example:
n = 15
print(bin(n)) # 0b1111 (binary)
print(oct(n)) # 0o17 (octal)
print(hex(n)) # 0xf (hexadecimal)
3. String Methods
Some commonly used methods:
Method Use
[Link]() Converts to uppercase
[Link]() Converts to lowercase
[Link]() Removes spaces from start & end
[Link](a,b) Replaces substring
[Link]() Splits string into list
[Link](sub) Finds position of substring
Example:
text = " Hello Python "
print([Link]()) # Hello Python
print([Link]()) # HELLO PYTHON
print([Link]("Python","World")) # Hello World
4. Text Files in Python
• A text file stores data in plain text form.
• Python allows opening, reading, and writing text files.
File Modes
• "r" → read
• "w" → write (overwrites)
• "a" → append (adds at end)
5. Text Files and Their Format
• TXT files: plain text.
• CSV files: values separated by commas.
• Log files: store logs/messages.
• Format decides how data is stored and read.
6. Writing Text to a File
Steps:
1. Open file in "w" or "a" mode.
2. Write using .write().
3. Close file.
Example:
f = open("[Link]", "w")
[Link]("Hello, this is a test file.")
[Link]()
7. Reading Text from a File
Steps:
1. Open file in "r" mode.
2. Use .read() or .readline().
3. Close file.
Example:
f = open("[Link]", "r")
print([Link]())
[Link]()
Summary for Exams:
• Encryption → hide data by changing characters.
• Number systems → use bin(), oct(), hex() for conversions.
• String methods → help in formatting & searching.
• Text files → open → read/write → close.
• Formats → TXT, CSV, Log.
• Write → write() ; Read → read().
Lists, Tuples, and Dictionaries in Python
1. Lists
• A list is a collection of items in order.
• Lists are mutable → values can be changed.
• Defined using square brackets [ ].
Example:
fruits = ["apple", "banana", "mango"]
print(fruits[0]) # apple
[Link]("orange") # add item
print(fruits) # ['apple', 'banana', 'mango', 'orange']
fruits[1] = "grapes" # change value
print(fruits) # ['apple', 'grapes', 'mango', 'orange']
Important List Methods:
• append(x) → add item
• remove(x) → remove item
• sort() → sort list
• len(list) → length
2. Tuples
• A tuple is like a list, but it is immutable (cannot be changed).
• Defined using round brackets ( ).
Example:
colors = ("red", "green", "blue")
print(colors[0]) # red
You cannot do colors[0] = "yellow" → gives error (because tuple is fixed).
Use tuples when you want fixed data (like days of week).
3. Dictionaries
• A dictionary stores data as key : value pairs.
• Defined using curly brackets { }.
• Keys are unique, values can be anything.
Example:
student = {"name": "Keerthana", "age": 20, "course": "Python"}
print(student["name"]) # Keerthana
student["age"] = 21 # update value
student["city"] = "Chennai" # add new key:value
print(student)
Important Dictionary Methods:
• keys() → list of keys
• values() → list of values
• items() → list of key-value pairs
• update() → add/update items
Quick Summary (for exam):
• List → ordered, mutable, uses [ ].
• Tuple → ordered, immutable, uses ( ).
• Dictionary → key-value pairs, uses { }.
Perfect Let’s write exam-style simple notes on Functions and Recursive Functions in Python.
Functions in Python
1. Defining Simple Functions
• A function is a block of code that performs a specific task.
• Functions make programs shorter and reusable.
• Defined using the def keyword.
Steps to define and use a function:
1. Use def keyword + function name.
2. Write code inside the function.
3. Call the function to run it.
Example – Simple Function:
def greet():
print("Hello, welcome to Python!")
greet() # function call
Example – Function with Parameters:
def add(x, y):
return x + y
print(add(5, 3)) # 8
2. Design with Recursive Functions
• A recursive function is a function that calls itself.
• Useful for problems like factorial, Fibonacci, etc.
• Needs a base condition to stop recursion.
Example – Factorial using Recursion:
def factorial(n):
if n == 0: # base case
return 1
else:
return n * factorial(n-1) # recursive call
print(factorial(5)) # 120
Example – Fibonacci using Recursion:
def fib(n):
if n <= 1:
return n
else:
return fib(n-1) + fib(n-2)
for i in range(6):
print(fib(i), end=" ") # 0 1 1 2 3 5