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 uppercase
  • lower() – Convert to lowercase
  • title() – Convert to title case
  • capitalize() – Capitalize first character
  • swapcase() – Swap cases

Searching and Checking

  • find()/index() – Find substring position
  • count() – Count substring occurrences
  • startswith() – Check if string starts with
  • endswith() – Check if string ends with
  • isalpha() – Check if all alphabetic
  • isdigit() – Check if all digits
  • isalnum() – Check if alphanumeric
  • isspace() – Check if all whitespace

Formatting

  • strip() – Remove leading/trailing whitespace
  • lstrip()/rstrip() – Remove left/right whitespace
  • center() – Center string in field
  • ljust()/rjust() – Left/right justify string
  • zfill() – Pad with zeros

Splitting and Joining

  • split() – Split string into list
  • splitlines() – Split at line breaks
  • join() – Join iterable with string as separator
  • partition() – Split at first occurrence
  • rpartition() – Split at last occurrence

Replacement

  • replace() – Replace substring
  • translate() – Character translation
  • expandtabs() – 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 is 0).
  • 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:

MethodReturns if not foundError Handling
find()-1No error
index()Raises ValueErrorNeeds 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

MethodPurposeReturns 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 substring0

These methods are case-sensitive. For case-insensitive searches, convert the string to lowercase/uppercase first.

Would you like additional examples or clarification? 😊

Similar Posts

  • Challenge Summary: Inheritance – Polygon and Triangle Classes

    Challenge Summary: Inheritance – Polygon and Triangle Classes Objective: Create two classes where Triangle inherits from Polygon and calculates area using Heron’s formula. 1. Polygon Class (Base Class) Properties: Methods: __init__(self, num_sides, *sides) python class Polygon: def __init__(self, num_sides, *sides): self.number_of_sides = num_sides self.sides = list(sides) 2. Triangle Class (Derived Class) Inheritance: Methods: __init__(self, *sides) area(self) python import math…

  • re module

    The re module is Python’s built-in module for regular expressions (regex). It provides functions and methods to work with strings using pattern matching, allowing you to search, extract, replace, and split text based on complex patterns. Key Functions in the re Module 1. Searching and Matching python import re text = “The quick brown fox jumps over the lazy dog” # re.search()…

  • circle,Rational Number

    1. What is a Rational Number? A rational number is any number that can be expressed as a fraction where both the numerator and the denominator are integers (whole numbers), and the denominator is not zero. The key idea is ratio. The word “rational” comes from the word “ratio.” General Form:a / b Examples: Non-Examples: 2. Formulas for Addition and Subtraction…

  •  Duck Typing

    Python, Polymorphism allows us to use a single interface (like a function or a method) for objects of different types. Duck Typing is a specific style of polymorphism common in dynamically-typed languages like Python. What is Duck Typing? 🦆 The name comes from the saying: “If it walks like a duck and it quacks like…

  • Python Functions

    A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. Defining a Function In Python, a function is defined using the def keyword, followed by the function name, a set of parentheses (),…

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

Leave a Reply

Your email address will not be published. Required fields are marked *