How do I check if a string contains ALL letters of the alphabet in python?

Maslor picture Maslor · Apr 5, 2016 · Viewed 20.5k times · Source

I am trying to write a python program that checks if a given string is a pangram - contains all letters of the alphabet.

Therefore, "We promptly judged antique ivory buckles for the next prize" should return True while any string that does not contain every letter of the alphabet at least once should return False.

I believe I should be using RegEx for this one, but I'm not sure how. It should look similar to this:

import sys
import re

input_string_array = sys.stdin.readlines()
input_string = input_string_array[0]

if (re.search('string contains every letter of the alphabet',input_string):
    return True
else:
    return False

Answer

Martijn Pieters picture Martijn Pieters · Apr 5, 2016

This is not something I'd solve with a regular expression, no. Create a set of the lowercased string and check if it is a superset of the letters of the alphabet:

import string

alphabet = set(string.ascii_lowercase)

def ispangram(input_string):
    return set(input_string.lower()) >= alphabet

Only if every letter of the alphabet is in the set created from the input text will it be a superset; by using a superset and not equality, you allow for punctuation, digits and whitespace, in addition to the (ASCII) letters.

Demo:

>>> import string
>>> alphabet = set(string.ascii_lowercase)
>>> input_string = 'We promptly judged antique ivory buckles for the next prize'
>>> set(input_string.lower()) >= alphabet
True
>>> set(input_string[:15].lower()) >= alphabet
False