Category Archives: Python

A Practical Guide to Hashing Passwords in Python with bcrypt

If you’re building any application that involves user accounts, there’s one security rule you absolutely cannot break: never, ever store passwords in plaintext. A single database breach could expose every user’s password, leading to a catastrophic loss of trust and security. The correct way to handle passwords is to hash them. In this guide, we’ll walk through the best way to do this in Python using the bcrypt library.

So, what’s wrong with common hashing algorithms like MD5 or SHA-1? They were designed to be fast. That’s great for verifying file integrity, but terrible for passwords. A fast algorithm means an attacker can try billions of password combinations per second against your leaked hashes. We need something that is intentionally slow. Enter bcrypt.

Bcrypt is a password-hashing function designed by Niels Provos and David Mazières. It has several key features that make it the gold standard for password security:

  • It’s Slow: By design, bcrypt is computationally expensive. This drastically slows down brute-force attacks.
  • It Includes Salt: Bcrypt automatically generates and incorporates a “salt” (a random string) into each hash. This means that even if two users have the same password, their stored hashes will be completely different.
  • It’s Adaptive: As computers get faster, you can increase the “cost factor” of bcrypt to make it even slower, keeping pace with hardware improvements.
Continue reading A Practical Guide to Hashing Passwords in Python with bcrypt

How to Count Occurrences of a Substring in a Python String

Ever found yourself needing to know how many times a specific character or word appears in a piece of text? Whether you’re analyzing user input, parsing log files, or just working with text data, counting occurrences is a fundamental task. Python, with its “batteries-included” philosophy, provides a simple and efficient built-in method for this: string.count().

In this tutorial, we’ll walk you through everything you need to know about using the count() method, from basic usage to more advanced examples.

Understanding the count() Method Syntax

The syntax for the count() method is straightforward and flexible. It’s called on a string object and looks like this:

string.count(substring, start, end)

Let’s break down the parameters:

  • substring: (Required) This is the character or sequence of characters you want to count within the main string.
  • start: (Optional) An integer specifying the index from where the search should begin. If omitted, it defaults to 0 (the beginning of the string).
  • end: (Optional) An integer specifying the index where the search should end. If omitted, it defaults to the end of the string.

The method returns an integer representing the total number of non-overlapping occurrences of the substring.

Continue reading How to Count Occurrences of a Substring in a Python String