Python 3中是否有内置功能,例如C 中的GetChar()

Is there a built-in function in Python 3 like getchar() in C++?

本文关键字:例如 中的 GetChar 功能 是否 内置 Python      更新时间:2023-10-16

我想在python中进行用户输入,该输入类似于 getchar(( c 中使用的函数。

C 代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
char ch;
while(1){
    ch=getchar();
    if(ch==' ') break;
    cout<<ch;
}
return 0;
}

输入:堆栈溢出

输出:堆栈

在上述代码中,当用户输入的空间比循环中断时。我想在python中使用 getchar(( type函数,如我在C 代码中使用的功能。

最简单的方法:

只使用拆分功能

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

使用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)

使用ReadChar:

使用pip install readchar

安装

然后使用以下代码

import readchar
str = ""
while(1):
    c = readchar.readchar()
    if c == " ":
        break
    str += c
print(str)

类似的事情应该做技巧

ans = input().split(' ')[0]

msvcrt提供 Windows 平台上的某些有用功能的访问。

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是一个内置模块,您可以在官方文档中阅读更多有关。

这将解决问题。(可能在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)

在这里,函数getchar()准备标准输入,一次只使用Cbreak一次读取一个字符,这意味着您不必按Enter for getchar()来读取键。此功能可与所有键一起使用,除了箭头键,在这种情况下,它将仅捕获逃生字符(27(

python 3解决方案:

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)
相关文章: