Comparing a string to multiple items in Python
If, OTOH, your list of strings is indeed hideously long, use a set:
accepted_strings = {'auth', 'authpriv', 'daemon'}
if facility in accepted_strings:
do_stuff()
Testing for containment in a set is O(1) on average.
Comparing string to multiple strings in python
Assuming you are trying to check whether your rail[x].index[b]
is either of ('WD' | 'POT' | 'NGI')
on each iteration,
Try the below snippet if it is the case,
route=''
for b in range(10):
route += ('-'+ rail[0].index[b] +'-') if (rail[x].index[b] in ('WD', 'POT', 'NGI'))
Quick Check:
print("WD" == ('WD' | 'POT' | 'NGI'))
TypeError: unsupported operand type(s) for |: 'str' and 'str'
print("WD" in ('WD' , 'POT' , 'NGI'))
True
Python 3: how to compare multiple strings in one line of code?
Use in
for containment tests.
categoryChoice = input("what is your category choice?")
if categoryChoice not in ("category1", "category 2", "category 3"):
print("not a valid choice")
http://ideone.com/e6n0Rr
By the way, if you're using Python 2, you should really use raw_input
instead of input
.
How to use IN to compare multiple strings as exact match in Python?
Your question is asking why:
"abc" in ("abc d")
returns True
and:
"abc" in ("abc d","ab")
returns False
.
Because the first expression is just wrapped in brackets it's akin to:
"abc" in "abc d"
Note that it doesn't act as a tuple because there's only 1 element.
Whereas
"abc" in ("abc d","ab")
Does use ("abc d","ab")
as a tuple (because of the comma meaning multiple elements), and so it searches for a matching element.
How to test multiple variables for equality against a single value?
You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:
if x == 1 or y == 1 or z == 1:
x
and y
are otherwise evaluated on their own (False
if 0
, True
otherwise).
You can shorten that using a containment test against a tuple:
if 1 in (x, y, z):
or better still:
if 1 in {x, y, z}:
using a set
to take advantage of the constant-cost membership test (i.e. in
takes a fixed amount of time whatever the left-hand operand is).
Explanation
When you use or
, python sees each side of the operator as separate expressions. The expression x or y == 1
is treated as first a boolean test for x
, then if that is False, the expression y == 1
is tested.
This is due to operator precedence. The or
operator has a lower precedence than the ==
test, so the latter is evaluated first.
However, even if this were not the case, and the expression x or y or z == 1
was actually interpreted as (x or y or z) == 1
instead, this would still not do what you expect it to do.
x or y or z
would evaluate to the first argument that is 'truthy', e.g. not False
, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).
So for the values x = 2; y = 1; z = 0
, x or y or z
would resolve to 2
, because that is the first true-like value in the arguments. Then 2 == 1
would be False
, even though y == 1
would be True
.
The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3
would fail for the same reasons. Use x == 1 or x == 2 or x == 3
or x in {1, 2, 3}
.
Comparing multiple string in one line (file) to single string in other file same line number
You are comparing every line of the first file to every line of the second file. What I think you want to do is compare each file line by line.
Something like this?
lines = []
with open('actual_results.txt') as actual, open('expected_results.txt') as expected:
try:
while True:
a, e = next(actual), next(expected)
if a in e.split(','):
lines.append((a, e, True))
else:
lines.append((a, e, False))
except StopIteration:
pass
with open('final_output_file.txt', 'w') as output:
for actual, expected, result in lines:
if result:
output.write('found\n')
else:
output.write('not found\n')
Related Topics
Convert Timestamps With Offset to Datetime Obj Using Strptime
Cron Job: How to Run a Script That Requires to Open Display
How to Install Python Developer Package
How to Control the Keyboard and Mouse with Python
A Function Callback Every Time a Key Is Pressed (Regardless of Which Window Has Focus)
Create Single Python Executable Module
How to Get the Python Call Stack with the Linux Perf
List All Currently Open File Handles
Listening for Global Key-Combinations in Python on Linux
Python Shutil.Copy Fails on Fat File Systems (Ubuntu)
Cannot Save Matplotlib Animation With Ffmpeg
Frequency Counts for Unique Values in a Numpy Array
Pythonic Way to Combine Two Lists in an Alternating Fashion
How to Write Dataframe to Postgres Table
Writing Python Lists to Columns in Csv
How to Show Pil Image in Ipython Notebook
Plt.Figure.Figure.Show() Does Nothing When Not Executing Interactively