Home > database >  how do i write a code in python that compares two strings A and B
how do i write a code in python that compares two strings A and B

Time:02-21

How can I compare two strings A and B, such that it will print 'true' if ALL the letters in A are in B but print 'false' if not. Note the two strings may not be of equal lengths. I tried using a for loop but it only tests the first letter of A

A=''
B=''
for c in A:
        if c not in B:
            print('False')
        else:
            print('True')

CodePudding user response:

You can convert your string to set():

A = "fedca"
B = "abcdefg"

if set(A) <= set(B):
  print("All the letters of A are contained in B")

CodePudding user response:

There are multiple ways to compare two strings in Python such as using the == operator.

Let's say below are your two strings.

A = "FirstString"
B = "SecondString"
print(A==B)

It will print false as both of the strings are not equal. You can define a function by yourself by passing two parameters in the functions.

  • Related