4

I'm experiencing a very odd problem in Python. These two didn't seem to help:

Validating user input strings in Python and fastest way to compare strings in python

I've written the following small program, test.py:

import sys
while True:
    print("\n")
    print("Type exit to exit: ")

    inputvar = str(input())
    print("Input: "+inputvar)

    if inputvar == 'exit':
        print("Exiting!")
        sys.exit("\n\nProgram quit.")
    else:
        print("Still here")

The current version doesn't seem to quit with exit, 'exit' or "exit". Using input() instead of str(input()) doesn't seem to make a difference, and using is or in instead of == doesn't make a difference either.

I'm using Python 3.2 on Windows 7.

5
  • Works for me in Python 3 exactly as posted. Commented May 6, 2015 at 10:22
  • 1
    input() already returns a string, so str(input()) won't make any difference. is compares identity, not equality, so is a bad choice for string comparisons; == is correct. If you're saying that 'exit' != 'exit' in your code, you have a serious problem; are you sure you haven't introduced some whitepace? Try inputvar.strip() or print(repr(inputvar)) to see what's going on. Commented May 6, 2015 at 10:22
  • 2
    Try adding inputvar.strip() just in case there is trailing whitespace for some reason. Commented May 6, 2015 at 10:23
  • works for me also, but on debian with python 3.4... Commented May 6, 2015 at 10:26
  • 1
    print(repr(inputvar)) gives 'exit\r', apparently a carriage return was added. It works with .strip() added! Commented May 6, 2015 at 10:27

2 Answers 2

7

There was a bug in Python 3.2.0 where the trailing \r was not removed from input() : details here. I suggest you upgrade (it was fixed very rapidly in 3.2.1). If you can't then:

inputvar = input().rstrip()
Sign up to request clarification or add additional context in comments.

Comments

-3

input() return a string

so no need to use str(input())

or you can use

inputvar = input().strip()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.