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

  • pop(), remove(), clear(), and del 

    pop(), remove(), clear(), and del with 5 examples each, including slicing where applicable: 1. pop([index]) Removes and returns the item at the given index. If no index is given, it removes the last item. Examples: 2. remove(x) Removes the first occurrence of the specified value x. Raises ValueError if not found. Examples: 3. clear() Removes all elements from the list, making it empty. Examples: 4. del Statement Deletes elements by index or slice (not a method, but a…

  • Data hiding

    Data hiding in Python OOP is the concept of restricting access to the internal data of an object from outside the class. 🔐 It’s a way to prevent direct modification of data and protect the object’s integrity. This is typically achieved by using a naming convention that makes attributes “private” or “protected.” 🔒 How Data…

  • recursive function

    A recursive function is a function that calls itself to solve a problem. It works by breaking down a larger problem into smaller, identical subproblems until it reaches a base case, which is a condition that stops the recursion and provides a solution to the simplest subproblem. The two main components of a recursive function…

  • String Alignment and Padding in Python

    String Alignment and Padding in Python In Python, you can align and pad strings to make them visually consistent in output. The main methods used for this are: 1. str.ljust(width, fillchar) Left-aligns the string and fills remaining space with a specified character (default: space). Syntax: python string.ljust(width, fillchar=’ ‘) Example: python text = “Python” print(text.ljust(10)) #…

  • Indexing and Slicing for Writing (Modifying) Lists in Python

    Indexing and Slicing for Writing (Modifying) Lists in Python Indexing and slicing aren’t just for reading lists – they’re powerful tools for modifying lists as well. Let’s explore how to use them to change list contents with detailed examples. 1. Modifying Single Elements (Indexing for Writing) You can directly assign new values to specific indices. Example 1:…

  • Type Conversion Functions

    Type Conversion Functions in Python 🔄 Type conversion (or type casting) transforms data from one type to another. Python provides built-in functions for these conversions. Here’s a comprehensive guide with examples: 1. int(x) 🔢 Converts x to an integer. Python 2. float(x) afloat Converts x to a floating-point number. Python 3. str(x) 💬 Converts x…

Leave a Reply

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