If I do the following in python,
string = raw_input('Enter the value')
it will return
Enter the value
and wait until I enter something into the prompt.
Is there a way to retrieve/collect the input I entered in a variable string?
I would like to use the entered value in the following way :
if dict.has_key('string'):
print dict[string]
Note: I previously made the error of using raw_string but I meant to say raw_input
there's no raw_string function in python's stdlib. do you mean raw_input?
string = raw_input("Enter the value") # or just input in python3.0
print(string)
This is very confusing ... I'm not familiar with a raw_string function in Python, but perhaps it's application-specific?
Reading a line of input in Python can be done like this:
import sys
line = sys.stdin.readline()
Then you have that line, terminating linefeed and all, in the variable line, so you can work with it, e.g. use it has a hash key:
line = line.strip()
if line in dict: print dict[line]
The first line strips away that trailing newline, since you hash keys probably don't have them.
I hope this helps, otherwise please try being a bit clearer in your question.
Is this what you want to do?
string = raw_input('Enter a value: ')
string = string.strip()
if string in dict: print dict[string]
import readline provides a full terminal prompt to the raw_input function. You get control keys and history this way. Otherwise, it's no better than the sys.stdin.readline() option.
import readline
while True:
value = raw_input('Enter a value: ')
value = value.strip()
if value.lower() == 'quit': break
Related
# TEST
import sys
a=sys.stdin.readline() # here the user inputs the string "HELLO"
print a
if a == "HELLO":
sys.stdout.write("GOOD_BYE")
print "AAAAAAAAAAA"
raw_input('\npress any key to continue')
Hi there. I am new to Python.
I am using Python 2.7.11.
I do not understand why control is not entering the if statement.
The output for the given code comes out as
HELLO
HELLO
AAAAAAAAAAA
press any key to continue
NOTE: The first "HELLO" above is user input
I've tried sys.stdout.flush() for the sys.stdout.write() statement. But it doesn't seem to help.
If I write the same code with a=raw_input() instead of the second line, it works perfectly fine.
Can anyone explain the reason for this.
readline comes with a newline character at the end. So what you are actually doing is comparing
HELLO\n == HELLO
which is actually false.
Do a.rstrip() to remove newline.
readline() function read newline character from standard input console. Please use rstrip("\n") to remove the same.
import sys
a=sys.stdin.readline().rstrip('\n')
print (a)
if a == "HELLO":
sys.stdout.write("GOOD_BYE")
print ("AAAAAAAAAAA")
raw_input('\npress any key to continue')
Try using 'in' instead of '==' in your if condition, sometimes the lines might have some hidden characters.
if "HELLO" in a:
You are pressing 'ENTER' after input string to send input. So your input is 'HELLO\n' while your if statement 'if' condition is 'a == "HELLO"'.
Use strip() method. The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).
So new working code :
import sys
a=sys.stdin.readline().rstrip('\n')
a=a.strip() # This will remove \n from input
print (a)
if a == "HELLO":
sys.stdout.write("GOOD_BYE")
print ("AAAAAAAAAAA")
raw_input('\npress any key to continue')
entry = input("Enter a word:")
if entry == whatever:
print("print this")
I keep getting error whatever is not defined. Why? I want to define it through input
whatever is a string which you are comparing your input with, so you need to put it in quotes. As in
if entry == 'whatever':
Now a small demo after the necessary edit will output
Enter a word:whatever
print this
Hi I apologize if this looks like homework, but I have been trying and failing to make this work, and I would really appreciate some expert help. I am trying to self-teach myself python.
I'm trying to solve problems in CodinGame and the very first one expects you to count the times input strings are passed to the program. The input string comes in two parts (eg. "Sina dumb"). I tried to use this:
count = int(sys.stdin.readline())
count = int(input())
count = int(raw_input()) #python2
But the program fails with:
ValueError: invalid literal for int() with base 10: 'Sina dumb\n'
depending on if I leave the newline in or not.
Please what am I doing wrong, and how can I make it better?
In python2.x or python 3.x
sys.stdin.readline() and input gives type str. So int("string") will produce error if string contains chars.
I think you need this(assuming)
import sys
input_var = input() # or raw_input() for python 2.x
# entering Sina dumb
>>>print(len(input_var.split()))
2
Update
If you want to count how much input you enter.Try this
import sys
from itertools import count
c = count(1)
while True:
input_var = input()
print ("you entered " + str(next(c)) + " inputs")
On one hand, in this case, python say you that you tried ton convert the String 'Sina dumb\n into integer that is not valid, and this is true. This probably triggered at the second line, int(input)
On the other hand, to solve your problem,one simple approach as each row you pass as input contains the end of line character \n you can for example get the input content, and split it at \n characters and count the size of the resulting list.
input() in python 3.x and raw_input()in python 2.x give a string. If a string contains anything but numbers it will give a ValueError.
you could try regular expression:
import re
line = input()
count = len(re.findall(r'\w+', line))
print (count)
I'm trying to get the behaviour of typical IM clients that use Return to send a text and Shift + Return to insert a linebreak. Is there a way to achieve that with minimal effort in Python, using e.g. readline and raw_input?
Ok, I heard it can be accomplished also with the readline, in a way.
You can import readline and set in configuration your desired key (Shift+Enter) to a macro that put some special char to the end of the line and newline. Then you can call raw_input in a loop.
Like this:
import readline
# I am using Ctrl+K to insert line break
# (dont know what symbol is for shift+enter)
readline.parse_and_bind('C-k: "#\n"')
text = []
line = "#"
while line and line[-1]=='#':
line = raw_input("> ")
if line.endswith("#"):
text.append(line[:-1])
else:
text.append(line)
# all lines are in "text" list variable
print "\n".join(text)
I doubt you'd be able to do that just using the readline module as it will not capture the individual keys pressed and rather just processes the character responses from your input driver.
You could do it with PyHook though and if the Shift key is pressed along with the Enter key to inject a new-line into your readline stream.
I think that with minimal effort you can use urwid library for Python. Unfortunately, this does not satisfy your requirement to use readline/raw_input.
Update: Please see also this answer for other solution.
import readline
# I am using Ctrl+x to insert line break
# (dont know the symbols and bindings for meta-key or shift-key,
# let alone 4 shift+enter)
def startup_hook():
readline.insert_text('» ') # \033[32m»\033[0m
def prmpt():
try:
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')
readline.parse_and_bind('C-x: "\x16\n"') # \x16 is C-v which writes
readline.set_startup_hook(startup_hook) # the \n without returning
except Exception as e: # thus no need 4 appending
print (e) # '#' 2 write multilines
return # simply use ctrl-x or other some other bind
while True: # instead of shift + enter
try:
line = raw_input()
print '%s' % line
except EOFError:
print 'EOF signaled, exiting...'
break
# It can probably be improved more to use meta+key or maybe even shift enter
# Anyways sry 4 any errors I probably may have made.. first time answering
I'm trying to solve a Krypto Problem on https://www.spoj.pl in Python, which involves console input.
My Problem is, that the Input String has multiple Lines but is needed as one single String in the Programm.
If I just use raw_input() and paste (for testing) the text in the console, Python threats it like I pressed enter after every Line -> I need to call raw_input() multiple times in a loop.
The Problem is, that I cannot modify the Input String in any way, it doesn't have any Symbol thats marks the End and I don't know how many Lines there are.
So what do I do?
Upon reaching end of stream on input, raw_input will return an empty string. So if you really need to accumulate entire input (which you probably should be avoiding given SPOJ constraints), then do:
buffer = ''
while True:
line = raw_input()
if not line: break
buffer += line
# process input
Since the end-of-line on Windows is marked as '\r\n' or '\n' on Unix system it is straight forward to replace those strings using
your_input.replace('\r\n', '')
Since raw_input() is designed to read a single line, you may have trouble this way.
A simple solution would be to put the input string in a text file and parse from there.
Assuming you have input.txt you can take values as
f = open(r'input.txt','rU')
for line in f:
print line,
Using the best answer here, you will still have an EOF error that should be handled. So, I just added exception handling here
buffer = ''
while True:
try:
line = raw_input()
except EOFError:
break
if not line:
break
buffer += line