[英]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: 在我的系统(numpy 1.6.2,python 3.2.2)上,输出如下所示:
>>>
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: 这不是与numpy
相关的:
>>> b"asd" == "asd"
False
In Python 3 bytes
objects don't compare equal to string
s. 在Python 3 bytes
对象中,对象不等于string
s。 So either: 所以要么:
b"val1"
instead of "val1"
so that the types match, 比较b"val1"
而不是"val1"
以便类型匹配, bytes
object into a string (like .decode('utf-8')
and compare with "val1"
. 将bytes
对象解码为字符串(如.decode('utf-8')
并与"val1"
进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.