Search and Validation Methods
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Validating user input before processing is essential for application stability. Python provides robust string validation predicates and search methods.
Prefixes and suffixes: startswith and endswith
Prefix is the text at the start of a string and suffix is the text at the end. startswith() and endswith() test them and return True or False.
Use .startswith() and .endswith() to inspect filenames, URLs, or protocols.
url = "https://mentornxt.com"print(url.startswith("https://"))print(url.endswith(".com"))Example 1 · Accepting only web addresses
link = "https://mentornxt.com/java"print(link.startswith("https://"))print(link.endswith((".com", ".org")))print(link.endswith(".pdf"))True False False
What this code does
startswithchecks the beginning of the text.endswithalso accepts a tuple, so one call can test several endings.- Each call returns True or False.
Both methods accept a single string or a tuple of prefixes to check: url.startswith(("http://", "https://")).
Searching: find() versus index()
find() is a string method that returns the index of the first match, or -1 when there is none. index() does the same but raises ValueError instead of returning -1.
Both methods locate the first index of a substring, but handle missing elements differently.
text = "python developer"print(text.find("dev"))print(text.find("java"))Example 2 · Splitting a log line at the colon
log = "ERROR: disk full"pos = log.find(":")print(pos)print(log[:pos])print(log.find("warning"))print("disk" in log)5 ERROR -1 True
What this code does
findgives the index of the colon, which is 5.- The slice
log[:pos]is the text before it. - A missing text gives -1, and
ingives a plain True or False.
.find() returns the starting index (7), or -1 if not found. In contrast, .index("java") would raise a ValueError.
Validation predicates: isdigit, isalpha, isalnum
Validation is checking that input has the expected shape before it is used, for example that a one-time code contains only digits and has the right length.
Test whether text consists purely of digits, alphabet letters, or alphanumeric characters.
otp = "849201"username = "alex99"print(otp.isdigit())print(username.isalnum())Example 3 · Checking a 6-digit account number
account_no = "894231"is_valid = account_no.isdigit() and len(account_no) == 6
print(f"Account: {account_no}")print(f"Is valid 6-digit account: {is_valid}")Account: 894231 Is valid 6-digit account: True
What this code does
- Checks that input consists strictly of numeric digits and has length 6.
- Returns True for valid OTP or account tokens.
Both checks evaluate to True. Notice that "12.5".isdigit() evaluates to False because the dot . is not a digit.
Next step
Check your understanding
9 quick questions