Reputation: 83
I'm looking for a way to insert separator in the input()
function.
To be clear, my script asks the user to input a timeout in H:MM:SS, and I'd like Python to insert :
by himself.
So if the user types "14250", I want the terminal to display 1:42:50 (during the input, not after pressing ENTER).
Is it possible in Python?
Upvotes: 2
Views: 1616
Reputation: 1932
There is a way to achieve the result (to some extent), tested on Windows 10, Python 3.7:
import msvcrt as osch
def main():
timestr = ''
print('Enter time in 24-hr format (hh:mm:ss): ', end='', flush=True)
for i in range(6):
ch = osch.getwch()
if i!=0 and i%2==0:
osch.putwch(':')
timestr += ':'
osch.putwch(ch)
timestr += ch
return timestr
if __name__ == "__main__":
res = main()
print('\n')
print(res)
Please note that the variable timestr
was created merely as storage for future use. Also, you can apply all kinds of validity checks. In my opinion, this method can't be used to parse a time input of type 14923
into 1:49:23
as lookahead is not available and there is no way of knowing whether user is going to input 12-hr time or 24-hr time. I am going for 24-hr time, which means, instead of 14923
, user will be required to enter 014923
.
Upvotes: 1
Reputation: 82899
Here's a version for Linux. It is based on and very similar to the version by anurag, but Linux's getch
modules does not know getwch
and putwch
, so those have to be substituted.
from getch import getche as getc
def gettime():
timestr = ''
print('Enter time in 24-hr format (hh:mm:ss): ', end='', flush=True)
for i in range(6):
timestr += getc() # get and echo character
if i in (1, 3): # add ":" after 2nd and 4th digit
print(":", end="", flush=True)
timestr += ':'
print() # complete the line
return timestr
time = gettime()
print("The time is", time)
Sample output:
Enter time in 24-hr format (hh:mm:ss): 12:34:56
The time is 12:34:56
I think this would also work on Windows with from msvcrt import getwche as getc
but I can not test this.
Upvotes: 2