0

I am trying to take count of how many times the user pressed the backspace key while giving input. I am using the following code but it doesn't seem like working for me any help would be appreciated TIA.

word = input()
count = 0
for letter in word:
    if keyboard.is_pressed('\b'):
        count += 1
print(count)
kewlabd
  • 21
  • 2
  • 1
    pretty sure that `\b` gets applied in the terminal and only the final string is sent to `input()` - so not possible with `input()` – Adam Smooch Aug 12 '21 at 18:19
  • 1
    You probably want the `keyboard` module: https://stackoverflow.com/a/44754161/10761353 – Adam Smooch Aug 12 '21 at 18:19
  • Right -- `input` accumulates the input buffer until the user hits `ENTER`. The method processes backspaces, so that the program never gets to see them. You need to start over, handling `KEYPRESS` events. Look up available packages to support individual keyboard events. – Prune Aug 12 '21 at 18:33

2 Answers2

0

You need to detect keypress event and construct the input yourself. input give you final result, this does not contain the '\b'

https://www.delftstack.com/howto/python/python-detect-keypress/

psedo code :

b_counter = 0
input = ''
while keypressed not 'Enter'
   if keypressed  is '\b' and len(input) > 0:
     input  == input [-1]
     b_counter += 1
   else:
      input = input + keypressed  

return input, b_counter 
DataYoda
  • 771
  • 5
  • 18
0

Install module

pip install pynput

And try this code

from pynput.keyboard import Key, Listener

global count
count = 0
def show(key):
    global count
    if(key == Key.backspace):
        count += 1
    if(key == Key.enter):
        return False

with Listener(on_press=show) as listener:
    listener.join()

word = input()
print(count)
pullidea-dev
  • 1,768
  • 1
  • 7
  • 23