Validating Strings in Python: How to Use isalnum, isalpha, and isdecimal

When processing user input, it is often necessary to perform validation checks, such as asking, “Is the input value only numbers?” or “Does it consist only of alphabets?”

Python’s string type (str) provides a set of convenient methods that inspect the content of a string and return True or False.

In this article, I will explain the main validation methods and their specific behaviors.

目次

Table of Contents

  1. List of String Validation Methods
  2. Checking for Letters, Numbers, and Alphanumerics
  3. Checking Case (Uppercase/Lowercase)
  4. Checking for Whitespace
  5. Practical Example: Input Check Function
  6. Summary

1. List of String Validation Methods

Below are the main methods introduced in this article. All of them check if the entire string meets the specific condition.

Method NameDescriptionExample (True)Example (False)
isalnum()Alphanumeric (Letters or Numbers)"abc123""abc-123" (Symbol)
isalpha()Letters only"abc""abc1" (Number)
isdecimal()Decimal numbers only"123""12.3" (Decimal point)
isascii()ASCII characters only"abc""あいう" (Non-ASCII)
isupper()All uppercase"ABC""Abc"
islower()All lowercase"abc""Abc"
isspace()All whitespace" "" a "

2. Checking for Letters, Numbers, and Alphanumerics

These are frequently used for format checking IDs or passwords.

text_alpha = "Python"
text_num = "12345"
text_alnum = "Python3"
text_symbol = "Python-3"

print(f"--- isalpha (Letters only) ---")
print(f"'{text_alpha}': {text_alpha.isalpha()}")  # True
print(f"'{text_alnum}': {text_alnum.isalpha()}")  # False (Contains numbers)

print(f"\n--- isdecimal (Numbers only) ---")
print(f"'{text_num}': {text_num.isdecimal()}")    # True
print(f"'{text_alnum}': {text_alnum.isdecimal()}")# False (Contains letters)

print(f"\n--- isalnum (Alphanumeric) ---")
print(f"'{text_alnum}': {text_alnum.isalnum()}")  # True
print(f"'{text_symbol}': {text_symbol.isalnum()}")# False (Contains hyphen)

Important Note:

In Python 3, isalpha() treats Unicode characters (such as Kanji or Hiragana) as letters (e.g., “日本語”.isalpha() returns True). If you want to limit the check to standard ASCII alphabets only, you need to combine it with isascii() or use regular expressions.


3. Checking Case (Uppercase/Lowercase)

These methods determine if a string is unified in uppercase or lowercase. Even if the string contains numbers or symbols, they are ignored, and the check is performed only on the alphabetic parts.

upper_str = "PYTHON 3.10"
lower_str = "python 3.10"
mixed_str = "Python 3.10"

print(f"--- isupper / islower ---")
print(f"'{upper_str}'.isupper(): {upper_str.isupper()}") # True
print(f"'{lower_str}'.islower(): {lower_str.islower()}") # True
print(f"'{mixed_str}'.islower(): {mixed_str.islower()}") # False

4. Checking for Whitespace

isspace() returns True if the string consists entirely of spaces, tabs (\t), or newlines (\n). If there is even a single visible character, it returns False.

space_only = "   \t\n"
text_with_space = " a b "

print(f"--- isspace ---")
print(f"'{space_only}': {space_only.isspace()}")      # True
print(f"'{text_with_space}': {text_with_space.isspace()}") # False

5. Practical Example: Input Check Function

Let’s combine these methods to create a simple password strength checker.

def check_password_strength(password):
    if len(password) < 8:
        return "Too short"
    if not password.isascii():
        return "Only ASCII characters are allowed"
    if password.isalnum():
        return "Include at least one symbol"
    if password.islower() or password.isupper():
        return "Mix uppercase and lowercase letters"
    
    return "OK"

# Test
print(check_password_strength("password123")) # No symbol
print(check_password_strength("Pass-123"))    # OK

Summary

  • isalnum: Alphanumeric (No symbols)
  • isalpha: Letters only
  • isdecimal: Numbers only (Integers)
  • isascii: ASCII characters (Alphanumeric + Symbols within ASCII range)
  • isspace: Whitespace only
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次