Reputation: 51
I'm trying to figure out how to check if line contains some substrings or not, if it does, print that string. If it doesn't, do nothing. For this do nothing thing, I found that there is a statement in Python that just holds space and does nothing, which is pass
so I used it. but the result is all strings are being printed no matter the condition.
try:
string = line.split(',')
if string[0] != 'Aa' or string[0] != 'Bb':
pass
print string
Upvotes: 1
Views: 83
Reputation:
That print string
line is independent of the if-statement. Meaning, it will be executed regardless of whether or not your condition is true.
You would need an else:
block to do what you want:
string = line.split(',')
if string[0] != 'Aa' and string[0] != 'Bb': # You need 'and' up here
pass
else:
print string # This will only be executed if the condition is false
But that is somewhat redundant. A better approach would be to just do:
string = line.split(',')
if string[0] == 'Aa' or string[0] == 'Bb':
print string
or maybe:
string = line.split(',')
if string[0] in {'Aa', 'Bb'}:
print string
Upvotes: 2
Reputation: 269
Just this:
string = line.split(',')
if string[0] == 'Aa' or string[0] == 'Bb':
print string
You don't need pass
Upvotes: 4
Reputation: 2930
try/except
is for error handling. I don't think you'll need it for this purpose.
string=line.split(',')
is correct. It'll split the string into a list of strings according to commas.
The problem is print string
. It's not inside the scope of the if
statement, so the if
statement has no effect on printing the string. You'll want something like this:
if string[0] != 'Aa' or string[0] != 'Bb':
pass
else:
print string
or better yet:
if string[0] == 'Aa' or string[0] == 'Bb':
print string
Upvotes: 2