close

How to compare individual characters in two strings in Python 3

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to compare individual characters in two strings in Python 3 in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to compare individual characters in two strings in Python 3?

  1. How to compare individual characters in two strings in Python 3?

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

  2. compare individual characters in two strings in Python 3

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

Method 1

Use zip:

def compare(a, b):
    for x, y in zip(a, b):
        if x == y:
            ...

Method 2

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read