简体   繁体   中英

How to input without newline in Python?

I am trying to create a simple file editor in Python via the console (called PyCons). Here is my current program:

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)

I used the end method to make sure that the existing code in the file was printed properly in its line format, but the input function does not have an end attribute. So, when I go to enter code in the editor:

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()

=====

...I get those big, nasty spaces between my inputs. Does anybody know a way to suppress the output of this space, similar to the end='' method used for the print function ?

EDIT: Project location for reference: https://repl.it/@xMikee/File-Editing

The newlines from the inputs are just local echos from the console. You see them on your screen but they aren't actually returned by the input function.

The real problem is with the newline you explicitly print before every line number. Remove the \\n so the line that prints line numbers becomes:

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

Furthermore, the file you're loading may not necessarily have a trailing newline in the end, so you need to detect that and print a newline if that's the case. Note what I added after your first for loop:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM