// Modules & Packages
Built-in String Constants
The idea
You need all lowercase letters. Or all digits. Or every punctuation character.
You could type them manually. Or you could let Python hand them to you.
The constants
import string
print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz
print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits) # 0123456789
print(string.punctuation) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.whitespace) # space, tab, newline, and others
These are strings — you can loop over them, check membership, slice them, use them anywhere a string works.
Practical uses
Check if a character is a letter or digit:
import string
char = "R"
print(char in string.ascii_letters) # True
print(char in string.digits) # False
Generate a random password:
import string
import random
alphabet = string.ascii_letters + string.digits
password = "".join(random.choice(alphabet) for _ in range(12))
print(password) # e.g. Xk9mT2rBqL4n
Validate that a string contains only letters:
import string
name = "Raven"
is_valid = all(ch in string.ascii_letters for ch in name)
print(is_valid) # True
mixed = "Raven123"
print(all(ch in string.ascii_letters for ch in mixed)) # False
Remove punctuation from a string:
import string
text = "Hello, World! How's it going?"
clean = "".join(ch for ch in text if ch not in string.punctuation)
print(clean) # Hello World Hows it going
Heads up!
- These are constants — strings, not functions. No parentheses.
ascii_letters=ascii_lowercase+ascii_uppercase- They only cover ASCII — no accented characters like
ă,â,î
What you should understand now
string.ascii_letters— all letters, upper and lowerstring.digits— 0 through 9string.punctuation— all punctuation characters- Use them with
in, loops, andrandom.choice()
// resources
// 0 comments
// No comments yet. Be the first.
// leave a comment