2

I have a string pulled from an excel spreadsheet, call it x. When using the print statement it prints the word PLANT

print(x)
PLANT

When I do the following:

if x == 'PLANT':
    print('YES')
else:
    print('NO')

It always prints NO.

I believe this is caused by the == checking something more fundamental than just the surface string. I tried to investigate further by using the ascii command, but this does not show any difference either.

ascii(x)

Are there any other commands I could try to distinguish x from PLANT and understand why they are not matching?


Things tested

repr(x)
'PLANT'

type(x)
<class 'str'>

ascii(x)
'PLANT'

Difference found:

id(x)
30805824

id('PLANT')
28515008
Phoenix
  • 4,386
  • 10
  • 40
  • 55

4 Answers4

2

There may be a chance of getting spaces around the letters. So it's better to do stripping the space characters before checking the condition.

if x.strip() == 'PLANT':
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

try this

x.strip() == 'PLANT':
bigC5012
  • 589
  • 1
  • 5
  • 19
1

I ran into similar issue, '\u00a0' can considered as space, if you read strings from a file, the chances are characters seem identical but completely different behind the scene.

solving this issue is not that much of a pain, however if you have this problem in your database, it might be difficult to look it up.

str1 = "Concrete Shear Walls"
str2 = "Concrete\u00a0Shear\u00a0Walls" # these two are identical on the surface
# Replace all non-breaking space characters with regular space characters
str2 = str2.replace('\u00a0', ' ')

if str1 == str2:
    print("The strings are equal.")
else:
    print("The strings are not equal.")

I hope this work for you.

Sina
  • 11
  • 2
0

I ran into this same issue and found that the value I had read from a file was NUL terminated ('\0') whereas the python string i was comparing against was not.

Rather than just calling strip which will remove spaces, call strip with the specific character you are attempting to remove.

if x.strip('\0') == "PLANT":
     print("match")

I found my issue using

print([ord(i) for i in x]) 

as suggested by Avinash Raj.

I realize this didn't seem to work for the original poster but since this solved a very similar problem I was facing I wanted to post here in case it helps others.

user8472
  • 113
  • 6