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.

miltonbhowmick
  • 324
  • 1
  • 5
  • 17

5 Answers5

15

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)
CodeIt
  • 3,492
  • 3
  • 26
  • 37
2

Something like this should do the trick

ans = input().split(' ')[0]
Mitch
  • 3,342
  • 2
  • 21
  • 31
  • 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 '22 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.

TommasoF
  • 795
  • 5
  • 21
run
  • 21
  • 1
2

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)

-1

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)
FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225