Skip to main content

How to Validate Repeated Inputs in Python

Creating repeated strings (e.g., "-" * 10) is simple in Python, but without proper validation, it can lead to TypeError, ValueError, or even Memory Errors if the repetition count is excessively large. Validating inputs ensures your application handles these cases gracefully.

This guide explores how to validate types, ranges, and patterns for string repetition, along with implementing custom exception handling for robust applications.

Basic String Repetition

In Python, the * operator repeats a string.

  • "abc" * 3 -> "abcabcabc"
  • "abc" * 0 -> "" (Empty string)
  • "abc" * -1 -> "" (Empty string)

While simple, it crashes if the multiplier is not an integer (TypeError) or freezes the system if the multiplier is huge.

Method 1: Type Validation (isinstance)

Before repeating, ensure the inputs are valid: the text must be a string, and the count must be an integer.

def safe_repeat(text, count):
# 1. Validate Text Type
if not isinstance(text, str):
raise TypeError(f"Text must be a string, got {type(text).__name__}")

# 2. Validate Count Type
if not isinstance(count, int):
raise TypeError(f"Count must be an integer, got {type(count).__name__}")

return text * count

# Test Cases
try:
print(safe_repeat("Tutorial", 3))
print(safe_repeat(123, 3)) # Raises TypeError
except TypeError as e:
print(f"Error: {e}")

Output:

TutorialTutorialTutorial
Error: Text must be a string, got int

Method 2: Range and Limit Validation

Allowing unlimited repetition is dangerous (e.g., text * 10**9 consumes gigabytes of RAM). Always enforce a maximum limit.

def bounded_repeat(text, count, max_count=1000):
# 1. Negative Check
if count < 0:
raise ValueError("Repetition count cannot be negative.")

# 2. Maximum Limit Check
if count > max_count:
raise ValueError(f"Count {count} exceeds maximum limit of {max_count}.")

return text * count

try:
print(bounded_repeat("A", 5))
print(bounded_repeat("A", 2000))
except ValueError as e:
print(f"Validation Error: {e}")

Output:

AAAAA
Validation Error: Count 2000 exceeds maximum limit of 1000.

Method 3: Pattern Validation (Regex)

Sometimes you only want to repeat strings that match specific criteria, such as alphanumeric characters only.

import re

def validate_pattern_repeat(text, count):
# Ensure text is alphanumeric (letters and numbers only)
if not re.fullmatch(r'[a-zA-Z0-9]+', text):
raise ValueError("Text must be alphanumeric.")

return text * count

try:
print(validate_pattern_repeat("Hello123", 2))
print(validate_pattern_repeat("Hello!", 2)) # Fails due to '!'
except ValueError as e:
print(f"Pattern Error: {e}")

Output:

Hello123Hello123
Pattern Error: Text must be alphanumeric.

Advanced: Custom Error Handling

For complex applications, defining custom exceptions allows you to pass detailed context (like the input values) up the call stack for logging or debugging.

class RepetitionError(Exception):
def __init__(self, message, text, count):
self.text = text
self.count = count
super().__init__(f"{message} (Input: '{text}' * {count})")

def robust_repeat(text, count):
if not isinstance(count, int) or count < 0:
raise RepetitionError("Invalid count", text, count)

return text * count

try:
robust_repeat("Test", -5)
except RepetitionError as e:
print(f"Custom Exception Caught: {e}")

Output:

Custom Exception Caught: Invalid count (Input: 'Test' * -5)

Conclusion

To validate string repetition safely:

  1. Check Types: Use isinstance() to ensure inputs are str and int.
  2. Enforce Limits: Always check count > max_limit to prevent memory exhaustion.
  3. Use Custom Exceptions: Create specific error classes for better debugging in large applications.