12

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.

Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
Jackie
  • 145
  • 1
  • 3
  • 12
  • 3
    What you've written simply copies y into s. What are you actually trying to do? – Prune Feb 11 '16 at 00:56
  • You're comparing every character in one string with every character in the other string, not just the corresponding characters. – Barmar Feb 11 '16 at 01:59

6 Answers6

17

Use zip:

def compare(a, b):
    for x, y in zip(a, b):
        if x == y:
            ...
L3viathan
  • 26,748
  • 2
  • 58
  • 81
4

Are you perhaps looking for something with logic similar to this? It chooses the alphabetically earlier character from each input string:

def compare(a,b):
    s = ""
    for i in range(len(a)):
        if a[i] < b[i]:
            s+=str(a[i])
        else:
            s+=str(b[i])
    return s

print compare ("seven", "eight")

Output:

eegen

The one-line version of this is

return ''.join(a[i] if a[i] < b[i] else b[i] for i in range(len(a)))
Prune
  • 76,765
  • 14
  • 60
  • 81
0
input(x)
input(y)
cnt = 0
 for char_val in x:
   if b[cnt] == char_val:
      print("match")
   else:
      print("mis-match")
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
0

Here is a complete function

def compare_strings(a,b):
    result = True
    if len(a) != len(b): print('string lengths do not match!')
    for i,(x,y) in enumerate(zip(a,b)):
        if x != y:
            print(f'char miss-match {x,y} in element {i}')
            result = False
    if result: print('strings match!')
    return result
gustavz
  • 2,964
  • 3
  • 25
  • 47
0
def twoStrings(s1, s2):
for i in range(len(s1)):
    for j in range(len(s2)):
        if s2[j] == s1[i]:
            return 'YES'
return 'NO'
  • 1
    format can be improved (the `return` and `for` keywords are on the same column than `def`) and it's always better to add a little explanation with code – ValLeNain Sep 27 '20 at 09:40
0

We can write simple and easy method to compare similar letters in two strings

def compare(a,b):
    s = ""
    t=""
    for x in a:
        for y in b:
            if x == y:
                t=x
        s=s+t
    print(s)

compare("xyz","axy")

Here first for loop will compare each letters in string and display all similar character.

think-maths
  • 917
  • 2
  • 10
  • 28