Programming Articles

Page 645 of 2547

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 712 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

How do nested functions work in Python?

Vikram Chiluka
Vikram Chiluka
Updated on 24-Mar-2026 9K+ Views

In this article, we will explain nested/inner functions in Python and how they work with examples. Nested (or inner) functions are functions defined within other functions that allow us to directly access the variables and names defined in the enclosing function. Nested functions can be used to create closures and decorators, among other things. Defining an Inner/Nested Function Simply use the def keyword to initialize another function within a function to define a nested function. The following program demonstrates the inner function in Python − Example # creating an outer function def outerFunc(sample_text): ...

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 convert date and time with different timezones in Python?

Vikram Chiluka
Vikram Chiluka
Updated on 24-Mar-2026 55K+ Views

In this article, we will show you how to convert date and time with different timezones in Python using the pytz library. Using astimezone() function Using datetime.now() function The easiest way in Python date and time to handle timezones is to use the pytz module. This library allows accurate and cross−platform timezone calculations and brings the Olson tz database into Python. Before you use it you'll need to install it using − pip install pytz Using astimezone() Function The astimezone() method converts a datetime object from one timezone to another. ...

Read More
Showing 6441–6450 of 25,466 articles
« Prev 1 643 644 645 646 647 2547 Next »
Advertisements