Python newline after input n characters

Question:

I need to create a script that read the user input, but after n characters python create a newline.

Example:

The user input the follow, after ‘H’,’0′ and ‘1’ the script create e
newline and start to read the input again.

ABCDEFGH

12345670

HIJKLMN1

8900000

I don’t want the user to press “Enter” after ‘H” or after the 8th character, instead python will put the cursor in a newline.

Asked By: Joao Vitorino

||

Answers:

You can detect a key press and if that char is G 7 or N you can add a new line “n”

You can check out this thread to see how you can detect keypresses.

Polling the keyboard (detect a keypress) in python

check out the bottom answer, it includes a package for easily detecting presses


Update

You will ned to use some keypress detection or something instead of while loop to do this “on the fly”, but I think this will get you started;

(though this is working, while() is only there to show where onpress or what you come up with should be, can be removed and script works fine)

import sys
#you need to change while() with on_press from a click listener or something
        while(True):
            bytes = sys.stdin.read() #reads "string"
            size_of_stdin = len(bytes) #reads string length
                if size_of_stdin > 7: ## size greater than 7 print;
                    print "You won!!" # prints
                    print "nn" # newlines

Reason you need to detect keypresses is that you have to “execute” the script manually now.

As in enter some text

1234567 (press enter)

then ctrl+z and enter again. (just to make it harder :p)

Then it looks like this in your terminal

1234567

^Z

You won!!

Hope you figure it out, let me know if anything is unclear or if you don’t find a way to detect presses and execute on after 7 presses.

Answered By: Kristian Martinsen

You can simply write n after the command, this works for input commands too. Then the cursor should show up in the next line rather than ending up just after the input/command.ending the command with n is the simplest way to put the cursor in a new line below

Answered By: Shafin Islam
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.