Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to input text between two strings?

Tags:

python

When I have this code

input('Write your name: ')

You can write your name after that string.

>>>Write your name: My name

But, how to have something display at the end of the input?

>>>Write your name: (Name)
>>>Write your name: (Name Name)
>>>Write your name: (Name Name Name)

So no matter what you write, the ')' character appears as you are writing?

like image 886
Fahem Moz Avatar asked Jul 19 '17 23:07

Fahem Moz


People also ask

How do you get text between two words in Python?

Using index() + loop to extract string between two substrings. In this, we get the indices of both the substrings using index(), then a loop is used to iterate within the index to find the required string between them.

How do you get text between two characters in Python?

With Python, you can easily get the characters between two characters using the string index() function and string slicing.


1 Answers

I would suggest the following implementation, which uses msvcrt to read a single char every time and act upon it (treating Enter and Backspace if encountered):

import msvcrt

def input_between_strings (s, t):
    res = ''
    while True:
        print(s, res, t, sep = '', end = ' \r')
        curr = msvcrt.getch()[0]
        if curr == 13:
            print()
            return res
        elif curr == 8:
            res = res[:-1]
        else:
            res += chr(curr)

With your case, you can call it like

result = input_between_strings('>>> Write your name: (', ')')
like image 174
Uriel Avatar answered Oct 17 '22 22:10

Uriel