Calculate Edit Distance between two strings

Published: 2017-08-03 23:18:06 +0000
Categories: Python,




Short snippet to calculate the edit distance (or Hamming Distance) between two strings in Python

The Hamming distance is just the number of differing bits within the string, so given two single char strings:

  • a: 01100001
  • b: 01100010
The Hamming distance would be 2 as the penultimate and last bit differ.

The edit distance is useful in basic cryptanalysis as for some cipher types (basically mechanisms where the key is repeated, i.e. ECB) it can help you discern the length of the key used - out of multiple tries at the keysize, the smallest (normalised) edit distance probably best indicates the key used.


import binascii

def char_to_bits(text):
    ''' Convert a character into a string of bits

    For example the letter 'a' would be returned as '01100001'

    bits = bin(int(binascii.hexlify(text), 16))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def computeHammingDistance(str1,str2):
    ''' Calculate the number of bits which differ between two strings (also known as the edit distance)
    distance = 0

    for i in range(len(str1)):

        # Convert each char to a bit string
        c1 = char_to_bits(str1[i])
        c2 = char_to_bits(str2[i])

        # Compare each of the bits and mark whether they differ
        for b in range(8):
            if c1[b] != c2[b]:
                distance = distance + 1

    return distance

Usage Example

>>> print computeHammingDistance('a','b')

>>> print computeHammingDistance('foo','fpo')

>>> print computeHammingDistance('foo','bar')





hamming, edit, distance, calculate, compute, analyse,

Latest Posts

Urldecode string (LUA)
FFMPEG Convert YUV444p to YUV420p (BASH)
Forcing FFMPEG to honour segment length in HLS Stream Creator (BASH)
Force CURL to place request to a specific IP (BASH)
Set a variable only if it is undefined (Javascript)
Ignore query string with Nginx caching proxy (NGinx)
Get breakdown of UK and non-UK votes for a Parliamentary Petition (Python)
Decompress Mozilla Firefox jsonlz4 bookmark backup files (Python)
Setting Git author details for a single repo (Git)
Checking Virtual Machine Resource Allocations with Libvirt (BASH)

Copyright © 2019 Ben Tasker | Sitemap | Privacy Policy
Available at and snippets.6zdgh5a5e6zpchdz.onion