Python:“打印”和“输入”在一行
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python:“打印”和“输入”在一行,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1783字,纯文字阅读大概需要3分钟。
内容图文
![Python:“打印”和“输入”在一行](/upload/InfoBanner/zyjiaocheng/745/4064bc2fc089431da143075508ae648b.jpg)
参见英文答案 > Possible to get user input without inserting a new line? 7个
如果我想在python中的文本之间添加一些输入,我怎么能在没有用户输入内容并按下回车后切换到新行?
例如.:
print "I have"
h = input()
print "apples and"
h1 = input()
print "pears."
应修改为输出到控制台的一行说:
I have h apples and h1 pears.
它应该在一条线上的事实没有更深层的目的,它是假设的,我希望它看起来那样.
解决方法:
如果我理解正确,你要做的是获得输入而不回应换行符.如果您使用的是Windows,则可以使用msvcrt模块的getwch方法获取输入的单个字符而不打印任何内容(包括换行符),然后打印字符(如果它不是换行符).否则,您需要定义一个getch函数:
import sys
try:
from msvcrt import getwch as getch
except ImportError:
def getch():
"""Stolen from http://code.activestate.com/recipes/134892/"""
import tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def input_():
"""Print and return input without echoing newline."""
response = ""
while True:
c = getch()
if c == "\b" and len(response) > 0:
# Backspaces don't delete already printed text with getch()
# "\b" is returned by getch() when Backspace key is pressed
response = response[:-1]
sys.stdout.write("\b \b")
elif c not in ["\r", "\b"]:
# Likewise "\r" is returned by the Enter key
response += c
sys.stdout.write(c)
elif c == "\r":
break
sys.stdout.flush()
return response
def print_(*args, sep=" ", end="\n"):
"""Print stuff on the same line."""
for arg in args:
if arg == inp:
input_()
else:
sys.stdout.write(arg)
sys.stdout.write(sep)
sys.stdout.flush()
sys.stdout.write(end)
sys.stdout.flush()
inp = None # Sentinel to check for whether arg is a string or a request for input
print_("I have", inp, "apples and", inp, "pears.")
内容总结
以上是互联网集市为您收集整理的Python:“打印”和“输入”在一行全部内容,希望文章能够帮你解决Python:“打印”和“输入”在一行所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。