2015-05-09 162 views
2

如果我想在Python中的文本之間插入一些輸入,我怎麼能沒有,在用戶輸入的東西后按下輸入,切換到一條新線?Python:「打印」和「輸入」在一行

如:

print "I have" 
h = input() 
print "apples and" 
h1 = input() 
print "pears." 

應該在一行進行修改,以輸出到控制檯說:

I have h apples and h1 pears. 

,它應該是在同一行的事實有沒有更深層次的目的,它是假設,我希望它看起來這樣。

+0

@jherran請從帖子的''
的去除,因爲他們不需要。 –

回答

0

如果我理解正確,你要做的是獲得輸入而不回顯換行符。如果您使用的是Windows,則可以使用msvcrt模塊的getwch方法獲取單個字符以便輸入而不打印任何內容(包括換行符),然後打印該字符(如果它不是換行符)。否則,你就需要定義一個殘培功能:

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.") 
+0

這個答案在功能上非常缺乏(沒有前向刪除,除了通過backspaces,KeyboardInterrupts,粘貼和歷史記錄之外的導航)。更好的答案提供[這裏](http://stackoverflow.com/a/41436173/6379747)和(這裏)[http://stackoverflow.com/a/41459565/6379747]。後者是這個答案的過度工程版本。 – ForgottenUmbrella

4

你可以做到以下幾點:

print 'I have %s apples and %s pears.'%(input(),input()) 

基本上你有,你有兩個輸入共振峯一個字符串。

編輯:

在一行讓一切有兩個輸入不(容易)實現的,據我所知。你可以得到最接近的是:

print 'I have', 
a=input() 
print 'apples and', 
p=input() 
print 'pears.' 

將輸出:

I have 23 
apples and 42 
pears. 

逗號符號防止print語句後的新線,但輸入後回報仍然存在,雖然。

+0

謝謝,我不知道格式化也可以像輸入那樣工作。 – Yinyue

+0

但是,文本只有在我輸入兩個數字後纔會出現 - 但它應該出現在數字中,例如。 「我有」 - 然後輸入數字,繼續文本。對不起,我沒有提到:我有Python 2.7。 – Yinyue

+0

@Yinyue看到更新後的答案。 – Wouter

2

雖然其他答案是正確的,但不推薦使用%,應該使用字符串.format()代替。這是你可以做的。

print "I have {0} apples and {1} pears".format(raw_input(), raw_input()) 

此外,從你的問題,目前還不清楚是否你使用,所以這裏是一個答案爲好。

print("I have {0} apples and {1} pears".format(input(), input())) 
+0

謝謝,這有幫助! – Yinyue