Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare individual characters in two strings in Python 3

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.

like image 992
Jackie Avatar asked Feb 11 '16 00:02

Jackie


People also ask

How do you compare individual characters in two strings in Python?

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.

How do you compare individual characters between two strings?

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);

How do you compare individual letters in Python?

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.

Can we compare characters in Python?

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.


1 Answers

Use zip:

def compare(a, b):
    for x, y in zip(a, b):
        if x == y:
            ...
like image 116
L3viathan Avatar answered Oct 21 '22 20:10

L3viathan