Bird
0
0

You receive user data as a list of strings representing ages: ['25', ' 30', 'twenty', '40', '']. Which code snippet correctly validates and sanitizes this data to keep only valid positive integers?

hard📝 Model Choice Q15 of 15
Agentic AI - Agent Safety and Guardrails
You receive user data as a list of strings representing ages: ['25', ' 30', 'twenty', '40', '']. Which code snippet correctly validates and sanitizes this data to keep only valid positive integers?
Avalid_ages = [age for age in ages if age.isdigit() and age > 0]
Bvalid_ages = [int(age.strip()) for age in ages if age.strip().isdigit() and int(age.strip()) > 0]
Cvalid_ages = [int(age) for age in ages if age.isnumeric()]
Dvalid_ages = [int(age) for age in ages if age.strip() != '']
Step-by-Step Solution
Solution:
  1. Step 1: Sanitize input by stripping spaces

    Use age.strip() to remove spaces before validation.
  2. Step 2: Validate with isdigit() and positive check

    Check if stripped string is digits only and convert to int to check > 0.
  3. Step 3: Convert valid strings to integers

    Use int(age.strip()) to convert valid strings to integers.
  4. Final Answer:

    valid_ages = [int(age.strip()) for age in ages if age.strip().isdigit() and int(age.strip()) > 0] -> Option B
  5. Quick Check:

    Strip spaces, check digits, convert to int > 0 [OK]
Quick Trick: Strip spaces before isdigit(), then convert and check > 0 [OK]
Common Mistakes:
  • Not stripping spaces before validation
  • Comparing strings directly to numbers
  • Including empty or non-digit strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Agentic AI Quizzes