|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stop making mediocre tutorials.The best tutorials are video! Camtasia Studio makes it easy to create engaging, buzz-building screen videos at any size, in any popular format. Download the free trial!
|
|
#1
|
|||
|
|||
|
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
|
|||
|
|||
|
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:
Quote:
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
|
|
#3
|
|||
|
|||
|
An easier way is probably to use the function raw_input(). It will strip the newline from the input.
|
|
#4
|
||||
|
||||
|
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. |
|
#5
|
|||
|
|||
|
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'. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > comparing user input against a string (newbie) |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|