This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: string comparison with ==
Type: behavior Stage: resolved
Components: Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: a1an, ezio.melotti, flox
Priority: normal Keywords:

Created on 2011-11-18 11:43 by a1an, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (4)
msg147854 - (view) Author: Alan (a1an) Date: 2011-11-18 11:43
Hello,
did I discover a python string comparison bug or is this behaviour expected and I am doing something wrong?

This is the code I run:
for line in lines[4:]:
	currColl=line.split(":")[1].strip()
	print "'",currColl,"'","==","'",collName,"'"
	if currColl == collName :
		return True
	else:
		print "not equal"

where currColl is a method parameter and lines is built from subprocess Popen like:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
lines=[]
for line in p.stdout.readlines():
	lines.append(line)
	
The output of the abovementioned code is:
' utm ' == ' utm10 '
not equal
' utm1000 ' == ' utm10 '
not equal
' utm100 ' == ' utm10 '
not equal
' utm10 ' == ' utm10 '
not equal
' utm1 ' == ' utm10 '
not equal

as you can see the fourth comparison should return True while it gives a "not equal" as the others.

Python info:
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2
msg147855 - (view) Author: Florent Xicluna (flox) * (Python committer) Date: 2011-11-18 11:50
collName is probably not what you expect.
You can print repr(collName), repr(currColl) to verify this.

It is not a bug on Python side.
msg147867 - (view) Author: Alan (a1an) Date: 2011-11-18 12:57
Using repr highlights the issue which lies in the behaviour of str.strip() which does not strip away null spaces as I would have expected:

' 'utm10\x00' ' == ' 'utm10' '
not equal

Changing the code to:
currColl=line.split(":")[1].strip().strip("\0")

works but I think strip() should already do that by default, shouldn't it?
msg147869 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2011-11-18 12:59
Nope, str.strip only strips whitespace, and \x00 is not considered whitespace:
>>> '\x00'.isspace()
False
History
Date User Action Args
2022-04-11 14:57:23adminsetgithub: 57636
2011-11-18 12:59:31ezio.melottisetresolution: works for me -> not a bug

messages: + msg147869
nosy: + ezio.melotti
2011-11-18 12:57:17a1ansetmessages: + msg147867
2011-11-18 12:06:44floxsetstatus: pending -> closed
2011-11-18 11:50:13floxsetstatus: open -> pending

nosy: + flox
messages: + msg147855

resolution: works for me
stage: resolved
2011-11-18 11:43:55a1ancreate