Classes and Objects in Python
Classes and Objects in Python
What are Classes and Objects?
In Python, classes and objects are fundamental concepts of object-oriented programming (OOP).
- Class: A blueprint or template for creating objects. It defines the attributes (data) and methods (functions) that the objects will have.
- Object: An instance of a class. It’s a concrete entity based on the class blueprint.
Real-world Analogy
Think of a class as a “cookie cutter” and objects as the “cookies” made from it. The cookie cutter defines the shape, and each cookie is an instance of that shape.
1. Using type() function
The type() function returns the type of an object.
python
text = "Hello, World!"
print(type(text)) # <class 'str'>
# Check if it's a string
if type(text) == str:
print("It's a string!")
else:
print("Not a string")
Finding String Class and String Methods in Python
There are several ways to explore the string class (str) and its methods in Python:
1. Using dir() function
The simplest way to see all string methods is to use the dir() function on a string object or the str class:
python
# View all string methods print(dir(str)) # Alternatively on a string object s = "hello" print(dir(s))
2. Using help() function
For detailed documentation on the string class and its methods:
python
# View complete string class documentation help(str) # Get help on a specific method help(str.upper)
4. Common String Methods (Python 3.x)
Here’s a categorized list of frequently used string methods:
Case Conversion
upper()– Convert to uppercaselower()– Convert to lowercasetitle()– Convert to title casecapitalize()– Capitalize first characterswapcase()– Swap cases
Searching and Checking
find()/index()– Find substring positioncount()– Count substring occurrencesstartswith()– Check if string starts withendswith()– Check if string ends withisalpha()– Check if all alphabeticisdigit()– Check if all digitsisalnum()– Check if alphanumericisspace()– Check if all whitespace
Formatting
strip()– Remove leading/trailing whitespacelstrip()/rstrip()– Remove left/right whitespacecenter()– Center string in fieldljust()/rjust()– Left/right justify stringzfill()– Pad with zeros
Splitting and Joining
split()– Split string into listsplitlines()– Split at line breaksjoin()– Join iterable with string as separatorpartition()– Split at first occurrencerpartition()– Split at last occurrence
Replacement
replace()– Replace substringtranslate()– Character translationexpandtabs()– Replace tabs with spaces
5. Practical Example Using String Methods
python
text = " Python Programming is Fun! "
# Case methods
print(text.upper()) # " PYTHON PROGRAMMING IS FUN! "
print(text.lower()) # " python programming is fun! "
# Search methods
print(text.find("Fun")) # 22
print(text.count("m")) # 2
# Formatting methods
print(text.strip()) # "Python Programming is Fun!"
print(text.center(40, '*')) # "******Python Programming is Fun!*******"
# Boolean checks
print(text.islower()) # False
print(text.isspace()) # False
# Split and join
words = text.strip().split()
print(words) # ['Python', 'Programming', 'is', 'Fun!']
print("-".join(words)) # "Python-Programming-is-Fun!"
find(), index(), and count(). Methods
In Python, strings are sequences of characters, and they come with several built-in methods for common operations. Here, we’ll explore three useful string methods: find(), index(), and count().
1. find() Method
The find() method searches for a substring within a string and returns the lowest index where the substring starts. If the substring is not found, it returns -1.
Syntax:
python
string.find(substring, start, end)
substring: The string to be searched.start(optional): Starting index (default is0).end(optional): Ending index (default is end of string).
Example:
python
text = "Hello, welcome to Python programming."
# Find 'welcome'
print(text.find("welcome")) # Output: 7
# Find 'Python' between index 10 and 20
print(text.find("Python", 10, 20)) # Output: -1 (not found in this range)
# Find a non-existent substring
print(text.find("Java")) # Output: -1
2. index() Method
The index() method is similar to find(), but if the substring is not found, it raises a ValueError instead of returning -1.
Syntax:
python
string.index(substring, start, end)
- Same parameters as
find().
Example:
python
text = "Hello, welcome to Python programming."
# Find 'Python'
print(text.index("Python")) # Output: 18
# Try to find a non-existent substring
print(text.index("Java")) # Raises ValueError: substring not found
Key Difference:
| Method | Returns if not found | Error Handling |
|---|---|---|
find() | -1 | No error |
index() | Raises ValueError | Needs try-except |
3. count() Method
The count() method returns the number of occurrences of a substring in the given string.
Syntax:
python
string.count(substring, start, end)
substring: The string to count.start(optional): Starting index.end(optional): Ending index.
Example:
python
text = "Python is fun, Python is powerful."
# Count 'Python'
print(text.count("Python")) # Output: 2
# Count 'is' between index 0 and 15
print(text.count("is", 0, 15)) # Output: 1
# Count a non-existent substring
print(text.count("Java")) # Output: 0
Summary Table
| Method | Purpose | Returns if not found |
|---|---|---|
find() | Finds the first occurrence of a substring | -1 |
index() | Finds the first occurrence (like find()) | Raises ValueError |
count() | Counts occurrences of a substring | 0 |
These methods are case-sensitive. For case-insensitive searches, convert the string to lowercase/uppercase first.
Would you like additional examples or clarification? 😊