comander derp comander derp - 1 month ago 5
Python Question

How do I compare a variable to a string in python?

Im new to this so Im sorry if this isn't the best way to ask the question...

here is the code -

import sys

print("What is ur name?")
name = sys.stdin.readline()

answer = "jack"

if name is answer :
print("ur awesome")

right now when I run it in cmd I don't get anything printed even though
I input - jack? thank you in advance


Firstly, replace is with ==. is checks whether the two underlying strings are the same entity (in memory) whereas == just wants to check if they have the same value.

Because the source of "jack" is coming from two sources (one from the user, another hard-coded by you) they are two seperate objects.

As @dawg mentioned you also have to use the .strip() to get rid of the newline when using sys.stdin.readline() for input. The best way to read input is to use the input() method in python3, or raw_input() in python2.

name = input('What is your name?\n')