#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2004
    Posts
    2
    Rep Power
    0

    comparing user input against a string (newbie)


    Hi, i'm trying to break out of a loop whenever user type in "q".
    However if ui=="q": never return true when i type in "q"!?!?
    what is the reason?


    while:
    print "Pls input the nominated text: "
    ui = str(sys.stdin.readline())
    if ui=="q":
    break
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2004
    Posts
    5
    Rep Power
    0

    Lightbulb Re: comparing user input against a string (newbie)


    I believe the problem is that sys.stdin.readline() will read in the whole line, including the carriage return ("\n") at the end. According to the Python docs:

    readline( [size])
    Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line).
    If you wish to remove the newline character try rstrip(). Here's your code modified to (hopefully) work:

    Code:
    while 1:  
         print "Pls input the nominated text: "  
         ui = sys.stdin.readline()  
         ui = ui.rstrip("\n")
         if ui=="q":  
              break
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    133
    Rep Power
    11
    An easier way is probably to use the function raw_input(). It will strip the newline from the input.
  6. #4
  7. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    A few similar examples of how to do this the easy way.

    Code:
    #!/usr/bin/env python
    
    user = ''
    
    while user != 'quit':
        user = raw_input('Pls input the nominated text: ')
    or

    Code:
    #!/usr/bin/env python
    
    user = raw_input('Pls input the nominated text: ')
    
    while user != 'quit':
        user = raw_input('Pls input the nominated text: ')
    Of course this exits if the user enters 'quit' but not hard to change to 'q'.

    Mark.
    programming language development: www.netytan.com Hula

  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2003
    Location
    Canada
    Posts
    543
    Rep Power
    24
    You should transform the text to be all upper-case letters or all lower-case letters. Then make the quit command 'q' and 'quit'.

    So if a user puts in QuIt, it will be transformed into 'quit'.

IMN logo majestic logo threadwatch logo seochat tools logo