I'm trying to compare the first character of two different strings (and so on) to form a new string based on those results. This is what I've tried using, however its comparing every element of each list to each other.
def compare(a,b):
s = ""
for x in a:
for y in b:
if x == y:
s+=str(x)
else:
s+=str(y)
It seems like such a simple question but I'm stuck.
is() function in Python. The is function compares two string by checking their ID. If both the strings have the same ID, it returns True, else it returns False. In this syntax, str1 and str2 are the strings that are to be compared using the is operator.
strcmp is used to compare two different C strings. When the strings passed to strcmp contains exactly same characters in every index and have exactly same length, it returns 0. For example, i will be 0 in the following code: char str1[] = "Look Here"; char str2[] = "Look Here"; int i = strcmp(str1, str2);
Compare Strings Character by Character in Python In Python, we can compare two strings, character by character, using either a for loop or a while loop. Since two strings can have different lengths, we must make sure that we only consider the smaller length for iterating over the strings for comparison.
Python comparison operators != : This checks if two strings are not equal. < : This checks if the string on its left is smaller than that on its right. <= : This checks if the string on its left is smaller than or equal to that on its right.
Use zip:
def compare(a, b):
for x, y in zip(a, b):
if x == y:
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With