Remove string quotes in array

Asked

Viewed 5,171 times

3

How can I remove single quotes from the result?

Typed user teste and key Esc to get out.

The program captures keystrokes and saves digit per digit in a list.

The list is hereby filled in:

lista ---> ["'t'", "'e'", "'s'", "'t'", "'e'", 'Key.esc']

The result of printing using the ''.join(lista) gets like this:

Result --> ’t'e'’s'’t'e'Key.Esc

I wish the end result would be like this:

testeKey.Esc

Code:

from pynput.keyboard import Key, Listener

def on_press(key): #tecla pressionada
    lista.append(str(key))

def on_release(key): #ao soltar a tecla
    if key == Key.esc:
        return False #interrompe programa

lista = []

with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

print('lista ---> ', lista)
print('Resultado ---> ', ''.join(lista))

3 answers

3


Just use replace and replace all quotes with an empty string (which is the same as removing them):

print('Resultado ---> ', ''.join(lista).replace("'", ""))

With this, the simple quotes (') are eliminated from the final result.

If you want, you can also use a comprehensilist on and do the replace on each item of the list separately:

print('Resultado ---> ', ''.join(s.replace("'", "") for s in lista))

Both print:

Result --> testeKey.Esc

Although in this case I find the first option simpler and more direct.


And if the character itself ' is typed?

I did a typing test a, afterward ', afterward ESC, and the list goes like this:

["'a'", '"\'"', 'Key.esc']

Note that the character ' is in double quotes.

Then the replace above does not work as it also removes the ' that was typed and the final result is a""Key.esc.

To fix this, we can create a function to treat this special case:

def replace_exceto_aspas(s):
    if '"\'"' == s:
        return "'"
    return s.replace("'", "")

That is, if it is the character itself ' in double quotes ("), I return a single quotation mark. Otherwise, I remove the single quotation marks.

Now just use the comprehensilist on, calling this function to all elements of the list, and finally joining everything with join:

print('Resultado ---> ', ''.join(replace_exceto_aspas(s) for s in lista))

The result will be:

Result --> a'Key.Esc


Alternative

But maybe it’s simpler to change the way you pick up the character being typed:

def on_press(key):  # tecla pressionada
    try:
        lista.append(key.char)
    except AttributeError:
        lista.append(str(key))

If the key you press has the attribute char - as is the case with alphanumeric characters - its value is added in the list (only the value of the character itself, without the quotation marks). If another non-alphanumeric key (like the ESC), he falls in the except and is added the value as you were already doing.

So you can just do ''.join(lista), without having to worry about removing the quotes (no longer need the replace, or the function I created above).

  • 1

    I appreciate your help and time to answer that question. Your reply was accurate and, coincidentally, I started using the indicated alternative. Thank you. :)

2

Just use the method .replace() if they occur throughout the process, or .strip() if they occur only at the beginning and/or completion:

a = '"sajdkasjdsak" "asdasdasds"' 

a = a.replace('"', '')
'sajdkasjdsak asdasdasds'

# ou, se ocorrerem apenas no início e no fim ...
a = a.strip('\"')
'sajdkasjdsak" "asdasdasds'

# ou, se ocorrerem apenas no início ...
a = a.lstrip('\"')

# ou, se ocorrerem apenas no final ...
a = a.rstrip('\"')
  • Thank you for your attention. I wish the final print result to look like this: testKey.Esc

0

If you use the replace as friends indicated is not your intention you can also use regular expressions using the function sub module re.

In case your code would look like this:

print('lista ---> ', lista)
lista = re.sub(r'\s', '', lista)
print('Resultado ---> ', lista)

Note: Don’t forget to import the module re in your code.
If you have not installed it use the command pip: In the terminal, turn pip3 install re
Ready, your module is installed. Now just use it :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.