简体   繁体   中英

How to compare numpy strings in Python 3

The following demonstrates the problem:

import io
import numpy as np

a = np.loadtxt(io.StringIO("val1 val2\nval3 val4"), \
               dtype=np.dtype([("col1", "S10"), ("col2", "S10")]))
print("looks weired: %s"%(a["col1"][0]))
assert(a["col1"][0] == "val1")

I don't understand how I should compare the strings. On my system (numpy 1.6.2, python 3.2.2) the output looks like this:

>>> 
looks weired: b'val1'
Traceback (most recent call last):
  File "D:/..../bug_sample.py", line 7, in <module>
    assert(a["col1"][0] == "val1")
AssertionError

This is not numpy -related:

>>> b"asd" == "asd"
False

In Python 3 bytes objects don't compare equal to string s. So either:

  • compare against b"val1" instead of "val1" so that the types match,
  • decode the bytes object into a string (like .decode('utf-8') and compare with "val1" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM