jabba
jabba

Reputation: 513

How to check if string contains exact match of string?

I'm trying to check if my dict keys can be found in a string. The thing is that my code doesn't match the entire string as such but goes through each character.

I tried like so:

val_dict= {'1/2 pint': 'half', '1': 'one', '5': 'five'}
text = 'I need 1/2 pint of beer'
for x in val_dict:
    if x in text:
        print(x, val_dict.get(x))

But I'm getting

1/2 pint half
1 one

Instead of only 'half'. How to solve it? '/' is not an escape character as far as I know.

Edit: Given the solutions provided in other topics, I tried regular expressions:

for x in val_dict:
    if re.search(rf"\b{x}\b", text, re.IGNORECASE):
        print(x + " match")

>>> 1/2 pint match
>>> 1 match

which is ok, because of \b but:

for x in val_dict:
    if re.search(rf"^{x}$", text, re.IGNORECASE):
        print(x + " match")

Should match exact occurrence, but gives no result. Why?

Please note that my dict keys may contain spaces, so splitting the text by spaces won't work.

Upvotes: 0

Views: 805

Answers (2)

Miguel Maramara
Miguel Maramara

Reputation: 11

You can try using Regular Expressions

import re

val_dict= {r'1/2': 'half', r'1[!/]': 'one', '5': 'five'}
#          ^"1/2"^          ^ 1 with NO SLASH

text = 'I need 1/2 pint of beer'
for x in val_dict:
    if re.match(x, text):
        print(x, val_dict.get(x))

Expected output:

1/2 half

You can tailor RegEx to much better fit your needs!

Upvotes: 0

idar
idar

Reputation: 610

This is the fix:

val_dict= {'1/2': 'half', '1': 'one', '5': 'five'}
text = 'I need 1/2 pint of beer'
for x in val_dict:
    if x in text.split(' '):
        print(x, val_dict.get(x))

Output

1/2 half

Upvotes: 1

Related Questions