12

I want to do user input in python which is similar to getchar() function used in c++.

c++ code:

#include<bits/stdc++.h>

using namespace std;
int main()
{
char ch;
while(1){
    ch=getchar();
    if(ch==' ') break;
    cout<<ch;
}
return 0;
}

Input: stack overflow

Output: stack

In the above code, when a space input from the user than the loop breaks. I want to do this in python using getchar() type function as I used in c++ code.

7
  • 2
    Possible duplicate of stackoverflow.com/questions/510357/… Feb 16, 2018 at 5:19
  • stackoverflow.com/questions/510357/… I have seen this but I need built-in function way in python 3. To more clarify my question, I have given c++ code. Feb 16, 2018 at 5:38
  • then your question title should have been something like "Is there a built-in function in Python 3 like getchar() in C++?". Regardless, it seems like the possible answers are in that original question. Feb 16, 2018 at 5:42
  • @milton. See my answer. The second method (using STDIN) is using built in function.
    – CodeIt
    Feb 16, 2018 at 5:42
  • @codelt Thanks a lot! it clears me Feb 16, 2018 at 5:47

5 Answers 5

14

Easiest method:

Just use split function

a = input('').split(" ")[0]
print(a)

Using STDIN:

import sys
str = ""
while True:
    c = sys.stdin.read(1) # reads one byte at a time, similar to getchar()
    if c == ' ':
        break
    str += c
print(str)

Using readchar:

Install using pip install readchar

Then use the below code

import readchar
str = ""
while(1):
    c = readchar.readchar()
    if c == " ":
        break
    str += c
print(str)
5
  • One more question! @Codelt Is it store in the buffer register when I am using sys.stdin.read(1) for each character input? Feb 16, 2018 at 5:51
  • @milton. Yes, the whole input is in the buffer and we are reading it byte by byte.
    – CodeIt
    Feb 16, 2018 at 5:53
  • Thank you so much for helping me @Codelt Feb 16, 2018 at 5:55
  • First example does not appear to work with Python 3. With input hello world it will split this into hello and world and the 0th element is hello. Not a single character. Apr 22, 2021 at 10:40
  • @FreelanceConsultant verify using input: stack overflow and output: stack
    – CodeIt
    Apr 24, 2021 at 5:19
2

Something like this should do the trick

ans = input().split(' ')[0]
1
  • Input requires the user to hit 'enter', that's not what's asked. Accidentally, the split() is useless here. Why did you add this ? To 'clean' the output ? Rather use strip() then.
    – orzel
    Dec 25, 2022 at 21:19
2

msvcrt provides access to some useful capabilities on Windows platforms.

import msvcrt
str = ""
while True:
    c = msvcrt.getch() # reads one byte at a time, similar to getchar()
    if c == ' ':
        break
    str += c
print(str)

msvcrt is a built-in module, you can read more about in the official documentation.

1

This will do the trick. (Probably does not work on Windows)

import sys
import termios

def getchar():
    old = termios.tcgetattr(sys.stdin)
    cbreak = old.copy()
    cbreak[3] &= ~(termios.ECHO|termios.ICANON)
    cbreak[6][termios.VMIN] = 1
    cbreak[6][termios.VTIME] = 0
    termios.tcsetattr(sys.stdin,termios.TCSADRAIN,cbreak)
    char = sys.stdin.read(1)
    termios.tcsetattr(sys.stdin,termios.TCSADRAIN,old)
    return char

if __name__ == '__main__':
    c = getchar()
    print("Key is %s" % c)

Here, the function getchar() prepares standard input to read only one character at a time using cbreak, meaning that you don't have to press enter for getchar() to read a key. This function works with all keys except for the arrow keys, in this case it will capture only the escape character (27)

0

Python 3 Solution:

a = input('')        # get input from stdin with no prompt
b = a.split(" ")     # split input into words (by space " " character)
                     # returns a list object containing individual words
c = b[0]             # first element of list, a single word
d = c[0]             # first element of word, a single character
print(d)

#one liner
c = input('').split(" ")[0][0]
print(c)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.