1

I need to read a single char from stdin and then unread it so that the next time an input method is called, that char should be included in the result. In C++, cin.putback does this. What is the equivalent in Python?

Please note that I don't need to intermingle different input methods/functions.

1

3 Answers 3

3

In Python 3, sys.stdin has a property called buffer that is an instance of io.BufferedReader and so has a peek method. This should allow you to do sys.stdin.buffer.peek(1)[:1], which would let you look at the next character in standard input without reading (consuming) it.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Anything similar for Python 2?
1

There isn't a simple analogue in Python.

Your best bet is probably to read the characters into an list in your program, and then later consume them from that list.

1 Comment

That will get dirty very soon unless I write some module doing it for me.
0

I found a Python module called CIn which does exactly what I want. It is available on GitHub: https://github.com/abhishekkr200802/CIn

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.