Home > Software engineering >  python how to match multistring input
python how to match multistring input

Time:06-24

Context: So what I am trying to do is

a = 'hello world'
b = 'Hi world and hello user'

Rightnow I was using

if a in b:
  return True

This does not works cause it tries to compare whole string of a in b

Is there a function in python where it compares a and b ignore the space and actually return true.

Sorry for poorly phrased question, also I cannot manipulate a and b since I am ingesting both from user

CodePudding user response:

Given two strings (sentences) the objective appears to be to determine if all words in one sentence occur in another. In which case:

def is_in(a, b):
    return set(a.split()).issubset(set(b.split()))

print(is_in('hello user', 'hi world and hello user'))
print(is_in('hello world', 'hi world and hello user'))
print(is_in('goodbye user', 'hi world and hello user'))

Output:

True
True
False

CodePudding user response:

A straightforward way would be:

import re

a = 'hell world'
b = 'Hi world and hello user'

def match(a,b):
    count = 0
    for a_wd in a:
        for b_wd in b:
            if re.findall('\\b'   a_wd   '\\b', b_wd):
                count  = 1
    print(str(count))
    if count >= len(a.split()):
        return True
    else:
        return False

output = match(a,b)
print(output)

CodePudding user response:

You could create a list of the words in a and then check if they are in b.


a = 'hello world'
b = 'hi world and hello user'

#Split the sentence into words
set_a = set(a.split(" "))
set_b = set(b.split(" "))

#check if all the items from 'a' are in 'b'
if set_a.issubset(set_b):
    return True

CodePudding user response:

"Is there a function in python where it compares a and b ignore the space and actually return true."

If you want to do that you could use a.replace(" ") in b but that would still yield False, so I'm going to make an assumption you're trying to check the words of a against b.

I think what you're trying to do is check if every word in a is in b. If that is the case, loop over a.split(). That way you aren't changing 'a' and you can easily check if they are all in b (word in b for word in a.split(), see the code below).

a = 'hello world'
b = 'Hi world and hello user'

# added []'s around [word in b] for clarity
check = all([word in b] for word in a.split())

print(check)
# >>> True
print(a)
# >> hello world < a stays unchanged 

CodePudding user response:

a = 'hello world'
b = 'Hi world and hello user'

def check_strings(string_1, string_2):
    if string_1.replace(" ", "") == string_2.replace(" ", "") :
        return  True
    return False
print(check_strings(string_1=a, string_2=b))
  • Related