Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
String Basics & CreationString Indexing & SlicingCommon String MethodsString Formatting EssentialsFinding & Replacing TextString Testing & ValidationRegular Expression BasicsText Splitting & JoiningPractical String Projects
Python/String Manipulation/String Testing Validation

✅ String Testing & Validation — Verify String Content

Learn to test what a string contains and validate data format.


🎯 Character Type Tests

Check if all characters in a string belong to a specific category:

# Numeric checks
print("12345".isdigit())      # True
print("12.45".isdigit())      # False (contains dot)
print("123a".isdigit())       # False (contains letter)

# Alphabetic checks
print("hello".isalpha())      # True
print("hello123".isalpha())   # False (contains numbers)
print("hello world".isalpha())# False (contains space)

# Alphanumeric checks
print("hello123".isalnum())   # True
print("hello 123".isalnum())  # False (contains space)

# Whitespace checks
print("   ".isspace())        # True
print("hello world".isspace())# False

💡 String Position Checks

Check the beginning and end of strings:

text = "Python programming"

# Check beginning
print(text.startswith("Python"))      # True
print(text.startswith("python"))      # False (case-sensitive)
print(text.startswith("Py"))          # True

# Check ending
print(text.endswith("programming"))   # True
print(text.endswith("ing"))           # True
print(text.endswith("gram"))          # False

# Membership test
print("pro" in text)          # True
print("gram" in text)         # True
print("xyz" in text)          # False

🎨 Case Checking

Test string case properties:

print("hello".islower())           # True
print("HELLO".isupper())           # True
print("Hello".isupper())           # False (not all upper)
print("HELLO".islower())           # False (not all lower)

# Title case check
print("Hello World".istitle())     # True
print("hello world".istitle())     # False
print("HELLO WORLD".istitle())     # False

📊 Common Testing Methods

MethodTestsExample
`isdigit()`All digits`"123".isdigit()` → `True`
`isalpha()`All letters`"abc".isalpha()` → `True`
`isalnum()`Letters and digits`"abc123".isalnum()` → `True`
`isspace()`All whitespace`" ".isspace()` → `True`
`isupper()`All uppercase`"ABC".isupper()` → `True`
`islower()`All lowercase`"abc".islower()` → `True`
`istitle()`Title case`"Hello World".istitle()` → `True`
`startswith()`Begins with`"hello".startswith("he")` → `True`
`endswith()`Ends with`"hello".endswith("lo")` → `True`
`in`Contains`"ll" in "hello"` → `True`

💡 Real-World Example: Form Validation

# Validate username
username = "john_doe"
if len(username) >= 3 and username.isalnum() or "_" in username:
    print("Valid username")
else:
    print("Invalid username")

# Validate password strength
password = "MyPass123!"
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
is_long_enough = len(password) >= 8

if has_upper and has_lower and has_digit and is_long_enough:
    print("Strong password")
else:
    print("Weak password")

# Validate postal code (all digits)
postal = "12345"
if postal.isdigit() and len(postal) == 5:
    print("Valid postal code")

🎯 Practical Pattern: Input Validation

def get_number_input():
    """Get and validate numeric input"""
    user_input = input("Enter a number: ")

    if user_input.isdigit():
        return int(user_input)
    else:
        print("Invalid! Please enter only digits.")
        return None

def get_email_input():
    """Get and validate email format"""
    email = input("Enter email: ")

    if "@" in email and "." in email:
        at_index = email.find("@")
        dot_index = email.rfind(".")
        if at_index < dot_index:
            return email

    print("Invalid email format")
    return None

🔑 Key Takeaways

ConceptRemember
Type tests`isdigit()`, `isalpha()`, `isalnum()` for character types
Position tests`startswith()` and `endswith()` for checking edges
Case sensitivityAll tests are case-sensitive
in operatorQuick way to check if substring exists
Combine checksUse `and`/`or` for complex validation

🔗 What's Next?

Ready for pattern matching? Learn Regular Expressions for powerful text searching.


Ready to practice? Challenges | Quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn