Python 3中是否有内置功能,例如C 中的GetChar()
Is there a built-in function in Python 3 like getchar() in C++?
我想在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)
相关文章:
- 如何使用文件中的文本,例如变量
- 初学者问题:如何使用这些晦涩难懂的命令,例如C++中的'RenderWindow'
- 我的 c++ 应用程序中的运行时间从 0 增加到 60 太快了(例如一毫秒或一微秒)
- 是否可以将"inf"分配给变量,例如 c++ 中的常规数值
- 如何返回一串字母数字字符中的最大值(例如-1A003B3)?
- 是否可以交换在 c++ 中作为函数 func(say) 中的参数传递的 const 向量的两个元素,例如:vector<int>func (const vector<int>&
- 将 csv 中的行(例如)转换为实际的行名
- 从函数中的指针返回对象,例如链接列表
- 如何为内置类型添加成员功能,例如C 中的整数
- Python 3中是否有内置功能,例如C 中的GetChar()
- 我想制作一个代码,将C 中的单个数字值分开.例如:12345 = 1 2 3 4 5
- 有没有办法用参数替换字符串,例如 C++ 中的 printf
- 逗号分隔字符串的总和,例如 O(n) 中的 4,1,3
- 是否可以在C++中推迟 const 变量的初始化,例如 Java 的"blank final"功能?
- C 中的两个比较运算符,例如Python
- 为什么lambda函数用于stl函数,例如sort(),c 中的max_element()函数以两个参数为输入
- 直接获取基于范围的循环中的元素类型 **例如"using"
- 如何在c 中留下一个声明的函数,例如haskell中的``undefined''
- 如何使用 c++ 反转句子字符串中的每个单词,例如"I love computer science"
- 如何编写一个程序,我可以像 Ubuntu 中的命令一样添加信息(例如:程序 -u "Hello World" )