Comparing two strings in Python is a common programming task, where we determine if two given strings are similar or not. This can be helpful in various application scenarios, such as data analysis and validation. In this tutorial, we will learn how to compare two strings in Python using a for loop method.
Step 1: Store the Strings
First, let’s store the two strings that we want to compare. We will store these strings in variables (e.g., str1 and str2).
1 2 |
str1 = "Python" str2 = "PyThOn" |
Step 2: Define the Function for Comparing Strings
Next, let’s define a function named compare_strings that accepts two strings as input and returns ‘True’ if the strings are equal and ‘False’ otherwise. This function will use the for loop to compare the characters of the strings one by one.
1 2 3 4 5 6 7 8 |
def compare_strings(string1, string2): if len(string1) != len(string2): return False for i in range(len(string1)): if string1[i] != string2[i]: return False return True |
Step 3: Call the Function and Print the Result
Finally, call the compare_strings function with our previously defined strings (str1 and str2) and print the result.
1 2 |
result = compare_strings(str1, str2) print(result) |
When you run this code, you should get the following output:
False
As the strings “Python” and “PyThOn” are not equal, the output is ‘False’.
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def compare_strings(string1, string2): if len(string1) != len(string2): return False for i in range(len(string1)): if string1[i] != string2[i]: return False return True str1 = "Python" str2 = "PyThOn" result = compare_strings(str1, str2) print(result) |
Conclusion
In this tutorial, we have learned how to compare two strings in Python using a for loop. Feel free to modify the code to suit your specific requirements, such as case-insensitive comparing or comparing strings of different lengths without returning ‘False’ immediately. Always remember that Python provides various built-in functions for string manipulations, which can enhance your string comparison operations. For more information about string operations, visit the official Python documentation.