How to Get MD5 of a String? A Python One-Liner

Rapid Answer: The following one-liner calculates the MD5 from the string 'hello world':

import hashlib as h;print(h.md5(b'hello world').hexdigest())

Background: MD5 message-digest is a vulnerable cryptographic algorithm to map a string to a 128-bit hash value. You can use it as a checksum on a given text to ensure that the message hasn’t been corrupted. However, you shouldn’t use it as a protection against malicious corruption due to its vulnerability. With modern hardware and algorithms, it’s easy to crack!

Problem: How to generate an MD5 sum from a string?

Example: Say, you have the following string text:

text = 'hello world'

And you want to convert it to the MD5 hash value:

5eb63bbbe01eeed093cb22bb8f5acdc3

We’ll discuss some methods to accomplish this next.

Table of Contents

Method 1: hashlib.md5() — Multi-Liner

The hashlib library provides a function md5() that creates an object that can calculate the hash value of a given text for you via the method update():

# Method 1: hashlib.md5()
import hashlib

m = hashlib.md5()
text = 'hello world'
m.update(text.encode('utf-8'))

print(m.hexdigest())
# 5eb63bbbe01eeed093cb22bb8f5acdc3

Make sure to encode the string as a Unicode string with the string.encode('utf-8') method. Otherwise, Python will throw an error.

Method 2: hashlib.md5() — Trivial One-Liner

As a one-liner, the code looks unreadable:

# Method 2: One-Liner
import hashlib; m = hashlib.md5(); m.update(text.encode('utf-8'));print(m.hexdigest())
# 5eb63bbbe01eeed093cb22bb8f5acdc3

We used the standard technique to one-linerize flat code snippets without indented code blocks. Learn more in our related tutorial.

Related Tutorial: How to One-Linerize Code?

Method 3: Improved One-Liner

You can slightly improve the code by using the b'...' string instead of the encode() function to make it a Unicode string:

# Method 3: One-Liner
import hashlib as h;print(h.md5(b'hello world').hexdigest())
# 5eb63bbbe01eeed093cb22bb8f5acdc3

I also initialized the md5 object with the Unicode string directly rather than using the update() method. The one-liner now has minimum number of characters—I don’t think it can be made even more concise! 😉

Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners Now!!

Author: Shantun Parmar

10 thoughts on “How to Get MD5 of a String? A Python One-Liner

  1. I don’t even know how I ended up right here, however I assumed this submit was once great.
    I don’t recognise who you are but definitely you are going to a well-known blogger in case
    you aren’t already. Cheers!

  2. I loved as much as you will receive carried out
    right here. The sketch is tasteful, your authored material stylish.
    nonetheless, you command get got an impatience over that
    you wish be delivering the following. unwell unquestionably come further
    formerly again as exactly the same nearly a lot often inside case you shield
    this hike.

  3. I have been surfing online more than 3 hours as of late, yet I by no means discovered any interesting article like yours.

    It is lovely price sufficient for me. In my opinion, if all website owners and bloggers made excellent content as you did, the net will likely be much more useful than ever before.

  4. My coder is trying to convince me to move to .net from PHP.

    I have always disliked the idea because of
    the costs. But he’s tryiong none the less. I’ve been using WordPress on numerous websites for about a year and
    am nervous about switching to another platform. I have heard good things
    about blogengine.net. Is there a way I can import all my
    wordpress content into it? Any kind of help would be really
    appreciated!

Leave a Reply

Your email address will not be published.