为什么这两个字符串不相等?

时间:2022-05-30 11:30:01

I'm trying to compare two strings in python and for some reason they just aren't matching.

我试图在python中比较两个字符串,由于某种原因它们只是不匹配。

I've made sure there's no whitespace and they're both string types, but still no luck, even when they're exactly the same.

我已经确定没有空格,它们都是字符串类型,但仍然没有运气,即使它们完全相同。

if versions['ksp_version'] is self.version:

The strings are both '1.0.2' and I've tried both is and == with no luck.

字符串都是'1.0.2',我试过这两个是和==没有运气。

Is there a better way to compare strings in python that I'm just missing?

有没有更好的方法来比较我刚刚缺少的python中的字符串?

EDIT: Some more context.

编辑:更多背景。

So, I added these lines and printed out the variables.

所以,我添加了这些行并打印出变量。

print versions['ksp_version']
print type(versions['ksp_version'])
print "===="
print self.version
print type(self.version)

And here's what we got.

这就是我们得到的。

1.0.2
<type 'str'>
====
1.0.2
<type 'str'>

Based on that, they look the same. They both have been stripped of whitespace using .strip().

基于此,它们看起来一样。他们都使用.strip()删除了空格。

1 个解决方案

#1


Hard to say without seeing the actual strings. When you read from a file, be sure to strip the line you're comparing to get rid of potential \ns at the end:

很难说没有看到实际的字符串。当你从一个文件中读取时,一定要去掉你要比较的那一行,最后摆脱潜在的\ ns:

with open("input.txt") as f:
  for line in f:
    print line == "asd"
    print line.strip() == "asd"

prints

False
True

for input.txt:

asd

is will only yield True for strings that are the same object, i.e. strings known for certain are initialized to the same value before runtime.

对于同一个对象的字符串,只会产生True,即在运行时之前将已知的字符串初始化为相同的值。

#1


Hard to say without seeing the actual strings. When you read from a file, be sure to strip the line you're comparing to get rid of potential \ns at the end:

很难说没有看到实际的字符串。当你从一个文件中读取时,一定要去掉你要比较的那一行,最后摆脱潜在的\ ns:

with open("input.txt") as f:
  for line in f:
    print line == "asd"
    print line.strip() == "asd"

prints

False
True

for input.txt:

asd

is will only yield True for strings that are the same object, i.e. strings known for certain are initialized to the same value before runtime.

对于同一个对象的字符串,只会产生True,即在运行时之前将已知的字符串初始化为相同的值。