Rajendra Dharmkar

Rajendra Dharmkar

160 Articles Published

Articles by Rajendra Dharmkar

Page 4 of 16

What is the correct way to define class variables in Python?

Rajendra Dharmkar
Rajendra Dharmkar
Updated on 24-Mar-2026 274 Views

Class variables are variables that are declared outside the __init__ method. These are static elements, meaning they belong to the class rather than to the class instances. These class variables are shared by all instances of that class. Basic Syntax Class variables are defined directly inside the class body, outside any method ? class MyClass: class_var1 = 123 class_var2 = "abc" def __init__(self): # Instance variables go here ...

Read More

What is difference between self and __init__ methods in python Class?

Rajendra Dharmkar
Rajendra Dharmkar
Updated on 24-Mar-2026 8K+ Views

In Python classes, self and __init__ serve different but complementary purposes. Understanding their roles is essential for object-oriented programming in Python. What is self? The self parameter represents the instance of a class. It allows you to access the attributes and methods of the class from within its methods. When you call a method on an object, Python automatically passes the object itself as the first argument. Example class Student: def set_name(self, name): self.name = name # self refers to the current ...

Read More

How to create instance Objects using __init__ in Python?

Rajendra Dharmkar
Rajendra Dharmkar
Updated on 24-Mar-2026 918 Views

The __init__() method is a special method in Python classes that automatically runs when you create a new instance of a class. It's commonly called a constructor and allows you to initialize object attributes with specific values. Basic __init__() Method Here's how to define a simple __init__() method ? class Student: def __init__(self): self.name = "Unknown" self.age = 0 self.grades = [] # Create an instance student1 ...

Read More

How to write a Python regular expression to match multiple words anywhere?

Rajendra Dharmkar
Rajendra Dharmkar
Updated on 24-Mar-2026 3K+ Views

Regular expressions provide a powerful way to match multiple specific words anywhere within a string. Python's re module offers several approaches to accomplish this task efficiently. Using Word Boundaries with OR Operator The most common approach uses word boundaries (\b) combined with the OR operator (|) to match complete words ? import re s = "These are roses and lilies and orchids, but not marigolds or daisies" r = re.compile(r'\broses\b|\bmarigolds\b|\borchids\b', flags=re.I | re.X) print(r.findall(s)) ['roses', 'orchids', 'marigolds'] Using Alternation Groups You can simplify the pattern by grouping alternatives within ...

Read More

How do you validate a URL with a regular expression in Python?

Rajendra Dharmkar
Rajendra Dharmkar
Updated on 24-Mar-2026 713 Views

Validating URLs in Python can be approached in several ways depending on your specific needs. You can check URL format with regular expressions, verify structure with urlparse, or test actual connectivity. Using Regular Expression for URL Validation A comprehensive regex pattern can validate most URL formats − import re def validate_url_regex(url): pattern = r'^https?://(?:[-\w.])+(?:[:\d]+)?(?:/(?:[\w/_.])*(?:\?(?:[\w&=%.])*)?(?:#(?:\w*))?)?$' return re.match(pattern, url) is not None # Test URLs urls = [ "https://www.example.com", "http://subdomain.example.com:8080/path?query=value", "invalid-url", "https://example.com/page#section" ...

Read More

How to read and write unicode (UTF-8) files in Python?

Rajendra Dharmkar
Rajendra Dharmkar
Updated on 24-Mar-2026 29K+ Views

Python provides built-in support for reading and writing Unicode (UTF-8) files through the open() function. UTF-8 is the most widely used encoding for text files as it can represent any Unicode character. Reading UTF-8 Files To read a UTF-8 encoded file, specify the encoding parameter when opening the file − # Create a sample UTF-8 file first with open('sample.txt', 'w', encoding='utf-8') as f: f.write('Hello World! 你好世界 🌍') # Read the UTF-8 file with open('sample.txt', 'r', encoding='utf-8') as f: content = f.read() print(content) ...

Read More

How to find and replace within a text file using Python?

Rajendra Dharmkar
Rajendra Dharmkar
Updated on 24-Mar-2026 498 Views

Finding and replacing text within files is a common task in Python. You can read a file, replace specific text, and write the result to a new file using built-in file operations and string methods. Basic Find and Replace The following example reads from 'foo.txt', replaces all occurrences of 'Poetry' with 'Prose', and writes the result to 'bar.txt' − # Create sample input file first with open('foo.txt', 'w') as f: f.write("Poetry is often considered the oldest form of literature.") f.write("Poetry today is usually written down, but is still ...

Read More

How to compare two strings using regex in Python?

Rajendra Dharmkar
Rajendra Dharmkar
Updated on 24-Mar-2026 2K+ Views

Comparing two strings using regex in Python allows you to find patterns, match substrings, or perform flexible string comparisons. The re module provides powerful functions like search(), match(), and findall() for string comparison operations. Basic String Comparison with re.search() The re.search() function checks if one string exists as a substring in another ? import re s1 = 'Pink Forest' s2 = 'Pink Forrest' if re.search(s1, s2): print('Strings match') else: print('Strings do not match') Strings do not match Using re.match() for Pattern ...

Read More

What is the difference between Python functions datetime.now() and datetime.today()?

Rajendra Dharmkar
Rajendra Dharmkar
Updated on 24-Mar-2026 2K+ Views

The datetime.now() and datetime.today() functions both return the current local date and time, but they differ in their parameters and precision capabilities. Key Differences The main difference is that datetime.now() accepts an optional timezone parameter (tz), while datetime.today() does not accept any parameters. Function Parameters Timezone Support Precision datetime.now() Optional tz Yes Higher precision possible datetime.today() None No Standard precision Using datetime.now() The datetime.now() function can work with timezones and may provide higher precision ? from datetime import datetime import pytz # Local time ...

Read More

How to compare date strings in Python?

Rajendra Dharmkar
Rajendra Dharmkar
Updated on 24-Mar-2026 1K+ Views

Python's datetime module makes comparing dates straightforward by supporting all comparison operators (, =, ==, !=). This is essential for date validations, sorting, and conditional logic in your applications. Basic Date Comparison Here's how to compare datetime objects using comparison operators ? from datetime import datetime, timedelta today = datetime.today() yesterday = today - timedelta(days=1) print("Today:", today.strftime("%Y-%m-%d")) print("Yesterday:", yesterday.strftime("%Y-%m-%d")) print() print("today < yesterday:", today < yesterday) print("today > yesterday:", today > yesterday) print("today == yesterday:", today == yesterday) Today: 2024-01-15 Yesterday: 2024-01-14 today < yesterday: False today > yesterday: True ...

Read More
Showing 31–40 of 160 articles
« Prev 1 2 3 4 5 6 16 Next »
Advertisements