Python_Cheat_Sheet_Explained_Strings_OOPs
Python_Cheat_Sheet_Explained_Strings_OOPs
====================================
SECTION 1: STRINGS IN PYTHON
====================================
1. String Basics:
-----------------
s = "hello world"
- Strings are sequences of characters.
- You can index them with s[0], slice with s[start:end], and use negative indexing.
2. len(s)
- Returns the number of characters in the string.
Example:
len("abc") -> 3
3. String Slicing:
s[0:5] -> 'hello'
- Returns a portion of the string from index 0 to 4.
4. Reversing a string:
s[::-1]
- Step -1 reverses the string.
5. String Methods:
------------------
- s.upper() - Converts to uppercase.
- s.lower() - Converts to lowercase.
- s.title() - Capitalizes each word.
- s.strip() - Removes leading/trailing spaces.
- s.find(sub) - Returns index of first occurrence.
- s.replace("a", "b") - Replaces all 'a' with 'b'.
8. String Formatting:
---------------------
name = "Alice"
f"Hello, {name}!" -> 'Hello, Alice!'
- f-strings allow inline variable usage.
- "{} {}".format("A", "B") also works.
9. Count characters:
--------------------
from collections import Counter
Counter("banana") -> {'a': 3, 'n': 2, 'b': 1}
====================================
SECTION 2: OBJECT ORIENTED PROGRAMMING (OOP)
====================================
def greet(self):
print("Hi, I'm", self.name)
2. Inheritance:
---------------
class Student(Person):
def __init__(self, name, roll):
super().__init__(name)
self.roll = roll
3. Encapsulation:
-----------------
class Bank:
def __init__(self):
self._protected = 100
self.__private = 200
class Cat:
def sound(self):
print("Meow")
5. Abstraction:
---------------
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): pass
@classmethod
def class_func(cls):
print("I know my class:", cls.__name__)
7. Dunder/Magic Methods:
------------------------
__str__, __init__, __len__, etc.
class Book:
def __str__(self):
return "Book object"
8. Composition:
---------------
class Engine:
def start(self):
print("Engine start")
class Car:
def __init__(self):
self.engine = Engine()
def start(self):
self.engine.start()
====================================
EXAM PREP TIPS
====================================
- Memorize syntax for string slicing and formatting.
- Practice creating and inheriting classes.
- Know difference between static/class methods.
- Use OOP principles clearly in code.