Home > Enterprise >  Using regex to look into a list
Using regex to look into a list

Time:08-05

This is my first question ever, so please bear with me here. I have below set of python code, but I expect a "match" to be printed, instead I get a "No match". What am I doing wrong?

Code:

import re
items = ("t1", "s1")

for i in items:
    x = re.search("t.", i)

if x:
  print("match")
else:
  print("No match")

output

No match

CodePudding user response:

Your if block is outside of for loop, thus only last value of it is checked. You should indent it like:

for i in items:
    x = re.search("t.", i)

    if x:
        print("match")
    else:
        print("No match")

CodePudding user response:

Your code goes like this:

  1. You take "t1"
  2. Check if it matches with "t."
  3. It matches, save true in x
  4. You take "s1"
  5. Check if it matches with "t."
  6. It does not match, save false in x
  7. check x and do something

Notice how you overwrite x to false at point 6? This is why your output is "no match"

  • Related