Legit python if statement?
I am new to Python and trying to build a practice project that reads some XML开发者_JS百科. For some reason this if statement is triggered even for blank whitespace lines:
if '<' and '>' in line:
Any ideas why?
Your code says (parethesised for clarity):
if '<' and ('>' in line):
Which evaluates to:
if True and ('>' in line):
Which in your case evaluates to true
when you don't intend to. So, try this instead (parenthesis are optional, but added for clarity):
if ('<' in line) and ('>' in line):
You probably want:
if ('<' in line) and ('>' in line):
Your version is being interpreted as this:
if ('<') and ('>' in line):
which is probably not what you meant.
Use parenthesis to make things super-obvious.
How certain are you that line
is genuinely empty when you hit a blank line in the file?
When you write '<' and '>' in line
the interpreter sees that as '<' and ('>' in line)
which isn't what you want: you're after something more like '<' in line and '>' in line
or all(x in line for x in '<>')
. None of those expressions, including your original, will be true when line
is empty, though. The incorrect form of the expression will however, give an incorrect answer when the string contains only '>'
.
>>> '<' and '>' in ''
False
>>> '<' and '>' in '<'
False
>>> '<' and '>' in '>' # Huh?
True
>>> 1 and 0 in [0] # Perhaps this will clarify matters
True
Regardless, don't parse XML by hand - use an XML parsing library, such as the xml.etree.ElementTree
module included in the standard library.
Try:
if '<' in line and '>' in line:
I'd suggest reading a book on Python before diving in, you'll avoid a lot of pitfalls :)
精彩评论