As it turns out, your string has new-lines (\n\n) at the end.
You can use
text = text.strip()
to remove any surrounding whitespace from your string.
For future cases, to check if your string has the content you think it has:
print(repr(text))
Answer from khelwood on Stack Overflowarrays - Python String Comparison is not working - Stack Overflow
Weird string comparison behavior
Why doesn't this IF statement work when comparing string?
python string comparison not working - Stack Overflow
You are testing for object identity:
UserArray[i] is userinput:
you really want to use equality instead:
UserArray[i] == userinput:
is tests if two object references are pointing to the same object. == tests if the values of two objects is equivalent.
Two strings that have the same contents (are equal), are not necessarily one and the same object:
>>> spam = 'foo bar baz'
>>> ham = 'foo bar baz'
>>> spam is ham
False
>>> spam == ham
True
>>> eggs = ham
>>> eggs is ham
True
CPython does use some tricks to save memory and improve performance, where small integers and some strings are interned; every time you try to create a new string or integer that is interned, instead of a new object, you get an already cached value. In those cases is tests return True only because you indeed have the same object, reused for you by the interpreter.
Note that the equality test can still be incorrect. There could be extra whitespace around the values, or other characters that are not immediately obvious when printed to the screen:
>>> val1 = 'frogeyedpeas'
>>> val2 = 'frogeyedpeas\t'
>>> val1 == val2
False
>>> print val1, val2
frogeyedpeas frogeyedpeas
>>> print repr(val1), repr(val2)
'frogeyedpeas' 'frogeyedpeas\t'
Try:
UserArray[i].strip(' \n') == userinput.strip(' \n')
As your input methods are different and you may have trailing spaces and or newlines in one and not the other.
I was looking for some reading material regarding the following example:
a = 'TEST' b = 'TEST' print(a is b) # prints true c = 'TEST1' c = c[:4] print(c) print(a is c) # prints false
The variable c also contains the string TEST yet it's coming back as false. Now I know this is because the is operator compares the identity rather than the value. However I don't quiet understand why a and b have the same identity. I can recall reading somewhere that this is an optimisation step by Python where it understands that it already created the string TEST so all the next times that it uses this string it points to the same identity rather than filling up the memory with copies.
I was wondering if anyone can point me to some reading material, preferably python docs, where it is explained that two variables that are initialised with the same value end up having the same identity. Thank you very much in advance.
EDIT: Found the answer myself after some more googling. It's called String Interning (https://en.wikipedia.org/wiki/String_interning)
I'm new to python and I have this section of code in my guess the number program:
wantplay=input('Do you want to play again? Enter yes or no.\n')
print(playagain)
while True:
if wantplay=='no' or 'No' or 'NO':
playagain=0
break
elif wantplay=='yes' or 'Yes' or 'YES':
break
else:
print('Please enter a valid answer')
print(playagain)
print(wantplay)There is a while loop around most of the program that checks the condition of the variable playagain so if the user doesn't want to play again they can enter some form of no and it should set playagain to zero so the program finishes. If they enter yes then it should not change the value of playagain so the program loops again. I know I still have to clean up the third case where they enter something else, that's not what my question is about.
The problem I'm having is that no matter what I enter as input playagain is set to zero and the program finishes. I added the print statements here so I could see what the playagain and wantplay variables are doing and I get the following output.
Do you want to play again? Enter yes or no.
yes
1
0
yes
And then the program doesn't loop. So playagain is 1 (as expected) before the conditional, it is 0 afterwards, and wantplay contains yes as I expect. Apparently the first block in the conditional is being executed and setting playagain to 0. Why? Am I comparing strings the wrong way or something?
EDIT: Thanks for the help everybody! I understand what I was doing wrong now, lots of good info here. I didn't know lower() or casefold() existed so that answers another question I had about accounting for capitalization in input. I was not sure how you would account for every possibility of caps and lower case and writing out every single one didn't seem like the right way.
I suspect line ends with a newline character, and it remains there throughout all of your replace operations. Then your comparison fails because "ExecutionOptimizer\n" doesn't equal "ExecutionOptimizer". You can discard the newline using strip:
line_no_spaces = line.strip().replace(" ","")
Use "is" key word. "==" is for equality testing
From a Python interpreter:
> a = 'tea'
> b = ''.join(['t', 'e', 'a'])
> a == b
True
> a is b
False
It would help even more if you would have provided an actual example.
In any way, your problem is the different string encoding in Python 2. entry.title is apparently a unicode string (denoted by a u before the quotes), while line is a normal str (or vice-versa).
For all characters that are equally represented in both formats (ASCII characters and probably a few more), the equality comparison will be successful. For other characters it won’t:
>>> 'Ä' == u'Ä'
False
When doing the comparison in the reversed order, IDLE actually gives a warning here:
>>> u'Ä' == 'Ä'
Warning (from warnings module):
File "__main__", line 1
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
You can get a unicode string from a normal string by using str.decode and supplying the original encoding. For example latin1 in my IDLE:
>>> 'Ä'.decode('latin1')
u'\xc4'
>>> 'Ä'.decode('latin1') == u'Ä'
True
If you know it’s utf-8, you could also specify that. For example the following file saved with utf-8 will also print True:
# -*- coding: utf-8 -*-
print('Ä'.decode('utf-8') == u'Ä')
== is fine for string comparison. Make sure you are dealing with strings
if str(line).lower() == str(entry.title).lower()
other possible syntax is boolean expression str1 is str2.
You seem to have a string processing error.
PlayerId seems to be a C-String being stored in a unicode String.
Background: C uses a nullbyte (\x00) to mark the end of a string. Since this nullbyte is in your string it ends up in the string representation of the object.
You can take a look here, for some reference. But without more code I am not sure about the cause/fix.
Have you tried type(playerId)?
edit: I don't know what python implementation you are using, for cpython look here
Unfortunately I am not to firm in interfacing c and python, however you could try to use PyString_FromString to convert it on the c side to a python string or use some handcrafted function (eg split with regex at the first unescaped 0).
Some interfacing libs are listed in this awnser
You can strip any non-printable characters like so
import string
player = ''.join(filter(lambda c: c in string.printable, player))