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:
- You take "t1"
- Check if it matches with "t."
- It matches, save
true
inx
- You take "s1"
- Check if it matches with "t."
- It does not match, save
false
inx
- check
x
and do something
Notice how you overwrite x
to false at point 6?
This is why your output is "no match"