Python 3 中是否有像 C++ 中的 getchar() 这样的内置函数?

mil*_*ick 10 c++ python input getchar

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

C++代码:

#include<bits/stdc++.h>

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

输入:堆栈溢出

输出:堆栈

在上面的代码中,当用户输入一个空格时,循环会中断。我想使用我在 c++ 代码中使用的getchar()类型函数在 python 中执行此操作。

Cod*_*eIt 11

最简单的方法:

只需使用拆分功能

a = input('').split(" ")[0]
print(a)
Run Code Online (Sandbox Code Playgroud)

使用标准输入:

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)
Run Code Online (Sandbox Code Playgroud)

使用读取字符:

安装使用 pip install readchar

然后使用下面的代码

import readchar
str = ""
while(1):
    c = readchar.readchar()
    if c == " ":
        break
    str += c
print(str)
Run Code Online (Sandbox Code Playgroud)


Mit*_*lin 2

像这样的事情应该可以解决问题

ans = input().split(' ')[0]
Run Code Online (Sandbox Code Playgroud)