簡體   English   中英

如何在Python中沒有換行符的情況下輸入?

[英]How to input without newline in Python?

我試圖通過控制台(稱為PyCons)在Python中創建一個簡單的文件編輯器。 這是我當前的程序:

def PyCons(f):
  file = open(f, "r")
  appe = open(f, "a")
  print("\n=====\nPyCons Editor, v1.2\nPython 3.6.1\n")
  global i
  i = 0
  for line in file:
    i += 1
    print(" {}|  ".format(i) + line, end='')
  for k in range(10000000000000):
    print("\n {}| ".format(i+1), end='')
    inp = input("")
    if inp == "@PyCons.save()":
      print("\n=====")
      break
    else:
      i += 1
      appe.write("\n" + inp)

我使用end方法來確保文件中的現有代碼以其行格式正確打印,但是input函數沒有end屬性。 因此,當我在編輯器中輸入代碼時:

PyCons("magic.html")    
...

=====
PyCons Editor, v1.2
Python 3.6.1

 1|  <p>Hello!</p>
 2|  <h1>Big text!</h1>
 3|  <h2>Smaller text!</h2>
#Should be no spaces here
 4|  <p>More stuff!</p>
#No spaces here either
 5|  @PyCons.save()

=====

...我在輸入之間得到了很大的,討厭的空間。 有誰知道一種抑制此空間輸出的方法,類似於用於print functionend=''方法?

編輯:供參考的項目位置: https : //repl.it/@xMikee/File-Editing

輸入中的換行符只是控制台中的本地回顯。 您可以在屏幕上看到它們,但input功能實際上並未返回它們。

真正的問題是在每個行號之前顯式打印的換行符。 刪除\\n以便打印行號的行變為:

print(" {}| ".format(i+1), end='')

此外,您要加載的文件不一定在末尾有換行符,因此您需要檢測到該情況並打印換行符。 請注意我在第一個for循環之后添加的內容:

def PyCons(f):
    file = open(f, "r")
    appe = open(f, "a")
    print("\n=====\nPyCons Editor, v1.2\nPython 3.6.1\n")
    global i
    i = 0
    for line in file:
        i += 1
        print(" {}| ".format(i) + line, end='')
    if not line.endswith('\n'):
        print()
    for k in range(10000000000000):
        print(" {}| ".format(i+1), end='')
        inp = input("")
        if inp == "@PyCons.save()":
            print("\n=====")
            break
        else:
            i += 1
            appe.write("\n" + inp)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM