Search code examples
autokey

How to wrap the select text in quotes ("") in Autokey?


I use the following script to add apostrophes ' around text when a specified hotkey is pressed:

text = clipboard.get_selection()
keyboard.send_key("<delete>")
keyboard.send_keys("'%s'" % text)

Changing the last line to keyboard.send_keys(""%s"" % text) doesn't work -- presumably the quotes have to be escaped.


Solution

  • Python 2: You need to use backslash escapes before the quotes that will be wrapped around the selected text:

    text = clipboard.get_selection()
    keyboard.send_keys("\"%s\"" % text)
    

    Python 3: Backslash escapes are no longer needed in Python 3 since you can use f-strings to do the replacements.

    This example wraps the text in double quotes:

    text = clipboard.get_selection()
    keyboard.send_keys(f'"{text}"')
    

    This example wraps the text in single quotes:

    text = clipboard.get_selection()
    keyboard.send_keys(f"'{text}'")