Member-only story
Stop Typing “abcdefghijklmnopqrstuvwxyz” in full! (Python)

I’m sure you’ve done this at some point in your Python journey. Maybe you need to solve a question requiring you to map a letter to the next, or whatever.
I’m here to inform you that you don’t have to do this!
The built-in “string” module
Built-in means that we don’t need to install anything using pip — we simply need to import it using the import
keyword
import string
This module contains a bunch of constants and functions relating to strings in Python eg. all english letters, punctuation etc
Using the “string” module
import string
print(string.ascii_lowercase) # lowercase letters
# abcdefghijklmnopqrstuvwxyz
print(string.ascii_uppercase) # uppercase letters
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.ascii_letters) # lowercase + uppercase letters
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.punctuation) # english punctuation
# !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(list(string.whitespace)) # whitespace characters
# [' ', '\t', '\n', '\r', '\x0b', '\x0c']
Here, ascii stands for “American standard code for information interchange”. If you don’t care, it just means “standard english letters and stuff”.
Using the string
module, we now no longer need to type stuff like
letters = 'abcdefghijklmnopqrstuvwxyz'
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
punctuation = '!”#$%&’()*+,-./:;<=>?@[\]^_`{|}~'
An example of my old code
We had to replace a
with b
, b
with c
, and so on.
letters = 'abcdefghijklmnopqrstuvwxyz'
d = {}
for i in range(len(letters)-1):
key = letters[i]
val = letters[i+1]
d[key] = val
d['z'] = 'a'
print(d)
# {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e', 'e': 'f', 'f': 'g', 'g': 'h',
# 'h': 'i', 'i': 'j', 'j': 'k', 'k': 'l', 'l': 'm', 'm': 'n', 'n': 'o',
# 'o': 'p', 'p': 'q', 'q': 'r', 'r': 's', 's': 't', 't': 'u', 'u': 'v',
# 'v': 'w', 'w': 'x', 'x': 'y', 'y': 'z', 'z': 'a'}