How to Compare Two Strings in Python
Compares two string values and returns a detailed report with equality, case-insensitive comparison, lengths, and uppercase versions.
Python code
29 linesdef compare_data(first_value, second_value):
"""Compare two string values and return a report."""
if first_value == second_value:
status = "MATCH"
else:
status = "DIFFER"
return {
"first_value": first_value,
"second_value": second_value,
"status": status,
"equal": first_value == second_value,
"first_length": len(first_value),
"second_length": len(second_value),
"first_upper": first_value.upper(),
"second_upper": second_value.upper(),
}
if __name__ == "__main__":
data_1 = "hello world"
data_2 = "Hello World"
results = compare_data(data_1, data_2)
print("Input 1:", data_1)
print("Input 2:", data_2)
print("Status:", results["status"])
print("Equal (case-sensitive):", results["equal"])
print("Equal (case-insensitive):", data_1.lower() == data_2.lower())
print("Lengths:", results["first_length"], "vs", results["second_length"])
Output
Input 1: hello world
Input 2: Hello World
Status: DIFFER
Equal (case-sensitive): False
Equal (case-insensitive): True
Lengths: 11 vs 11
How it works
The function compare_data uses the == operator to perform a case-sensitive comparison, which is the simplest way to check if two strings are identical. It also returns auxiliary info like lengths and uppercase versions, making the report reusable. The if __name__ == "__main__" guard runs the demo only when the script is executed directly, not when imported. The case-insensitive check in the main block calls .lower() on both values to normalize them before comparison. This pattern is handy for quick debugging or validation tasks.
Common mistakes
- Using `is` instead of `==` for string comparison, which checks identity, not equality.
- Forgetting to normalize case with `.lower()` when case-insensitive comparison is intended.
- Assuming `len()` works on non-string types, causing a TypeError if the input is a number.
- Comparing strings with trailing whitespace differences that are not immediately visible.
Variations
- Use `casefold()` instead of `lower()` for more aggressive case normalization that handles Unicode edge cases.
- Leverage `difflib.SequenceMatcher` to get a similarity ratio for fuzzy comparisons.
Real-world use cases
- Validating user input against expected values in a config or CLI argument parser.
- Checking if two API responses or database field values match before deciding on an update.
- Implementing a simple audit log that records what changed when comparing snapshots of text data.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.