130

I have a python Code that will recognize speech using the Google STT engine and give me back the results but I get the results in strings with "quotes". I don't want that quotes in my code as I will use it to run many commands and it doesn't work. I haven't tried anything so far as I didn't get anything to try! This is the function in the python code that will recognize speech:

def recog():
    p = subprocess.Popen(['./speech-recog.sh'], stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE)
    global out,err
    out, err = p.communicate()
    print out

This is speech-recog.sh:

#!/bin/bash

hardware="plughw:1,0"
duration="3"
lang="en"
hw_bool=0
dur_bool=0
lang_bool=0
for var in "$@"
do
    if [ "$var" == "-D" ] ; then
        hw_bool=1
    elif [ "$var" == "-d" ] ; then
        dur_bool=1
    elif [ "$var" == "-l" ] ; then
        lang_bool=1
    elif [ $hw_bool == 1 ] ; then
        hw_bool=0
        hardware="$var"
    elif [ $dur_bool == 1 ] ; then
        dur_bool=0
        duration="$var"
    elif [ $lang_bool == 1 ] ; then
        lang_bool=0
        lang="$var"
    else
        echo "Invalid option, valid options are -D for hardware and -d for duration"
    fi
done

arecord -D $hardware -f S16_LE -t wav -d $duration -r 16000 | flac - -f --best --sample-rate 16000 -o /dev/shm/out.flac 1>/dev/shm/voice.log 2>/dev/shm/voice.log; curl -X POST --data-binary @/dev/shm/out.flac --user-agent 'Mozilla/5.0' --header 'Content-Type: audio/x-flac; rate=16000;' "https://www.google.com/speech-api/v2/recognize?output=json&lang=$lang&key=key&client=Mozilla/5.0" | sed -e 's/[{}]/''/g' | awk -F":" '{print $4}' | awk -F"," '{print $1}' | tr -d '\n'

rm /dev/shm/out.flac

This was taken from Steven Hickson's Voicecommand Program made for Raspberry Pi

2
  • 1
    do you mean additional quotes to the quotes that represent a string in Python? Include the command and output that you have, and what you specifically want.
    – ivan7707
    Dec 3, 2016 at 18:10
  • There are many duplicates for "[python] remove string quotes"
    – smci
    Dec 3, 2016 at 18:41

8 Answers 8

234

Just use string methods .replace() if they occur throughout, or .strip() if they only occur at the start and/or finish:

a = '"sajdkasjdsak" "asdasdasds"' 

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

# or, if they only occur at start and end...
a = a.strip('\"')
'sajdkasjdsak" "asdasdasds'

# or, if they only occur at start...
a = a.lstrip('\"')

# or, if they only occur at end...
a = a.rstrip('\"')
3
  • 4
    In my situation escaping the double quote didn't work so I used this instead...a = a.strip(chr(34))
    – Dan
    Feb 20, 2020 at 1:56
  • 5
    why are you escaping the double quotes (")... using a.strip('"') is enough Jan 28, 2022 at 17:56
  • 1
    @VivekPuurkayastha: yes you're correct, I escape the quote both for visual clarity and from general force of habit, so that if it's then pasted into some other quoted string it remains a quote character, and doesn't blow things up.
    – smci
    Jan 28, 2022 at 18:00
23

You can use eval() for this purpose

>>> url = "'http address'"
>>> eval(url)
'http address'

while eval() poses risk , i think in this context it is safe.

5
  • also worked for me. Thanks @koliyat9811 I was getting string like '\\'Acknowledged\\'' by using eval i got 'Acknowledged'
    – Sony Khan
    May 21, 2019 at 6:03
  • 7
    literal_eval() (docs) is much safer than eval()
    – timvink
    May 8, 2020 at 17:13
  • 3
    What is the risk of using eval, if I may ask?
    – Nwoye CID
    Feb 26, 2021 at 13:42
  • @NwoyeCID Look up "python eval security"; but you can start here: realpython.com/python-eval-function/…
    – Murphy
    Mar 12, 2021 at 18:51
  • Careful! Both eval and literal_eval will do much more than just strip the quotes – they will also silently evaluate all escape sequences in the string. A valid escape will silently be converted (eval("'\xab'") gives '«'), while any invalid escape or invalid syntax (!!!) will result in an error – try eval("'\user'") or eval("'\images\raw'"). Jun 1 at 8:13
11

There are several ways this can be accomplished.

  • You can make use of the builtin string function .replace() to replace all occurrences of quotes in a given string:

    >>> s = '"abcd" efgh'
    >>> s.replace('"', '')
    'abcd efgh'
    >>> 
    
  • You can use the string function .join() and a generator expression to remove all quotes from a given string:

    >>> s = '"abcd" efgh'
    >>> ''.join(c for c in s if c not in '"')
    'abcd efgh'
    >>> 
    
  • You can use a regular expression to remove all quotes from given string. This has the added advantage of letting you have control over when and where a quote should be deleted:

    >>> s = '"abcd" efgh'
    >>> import re
    >>> re.sub('"', '', s)
    'abcd efgh'
    >>> 
    
8

The easiest way is:

s = '"sajdkasjdsaasdasdasds"' 
import json
s = json.loads(s)
4
  • how could '"sajdkasjdsaasdasdasds"' be json object?
    – goodahn
    May 6, 2021 at 2:06
  • 1
    a string (including with quotes) is a valid json string
    – Ryan
    May 7, 2021 at 9:47
  • Thank you! I tested double quotation again and get it!
    – goodahn
    May 15, 2021 at 5:53
  • Note that JSON will interpret several escape sequences automatically. This is likely not intended when just stripping quotes, and will produce unexpected output for any string using `` such as Windows paths. Jun 1 at 8:20
5

You can replace "quote" characters with an empty string, like this:

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

In your case, you can do the same for out variable.

5

This will remove the first and last quotes in your string

import ast

example = '"asdfasdfasdf"'
result = ast.literal_eval(example)

print(result)

Output:

asdfasdfasdf
3
if string.startswith('"'):
    string = string[1:]

if string.endswith('"'):
    string = string[:-1]
4
  • 5
    The string methods strip(), lstrip(), rstrip() are for this.
    – smci
    Dec 3, 2016 at 18:16
  • 5
    lstrip() removes all characters of the same type from the left. '""""hello'.lstrip('"') = 'hello'. This may not be what OP wants. Dec 3, 2016 at 18:19
  • Also, do you not think this approach is a bit naive? What if the quotes he wants to remove are in the middle of his string? Your solution would break. Dec 3, 2016 at 18:22
  • @smci I wasn't talking to you. I was talking to Harald. Dec 3, 2016 at 18:25
3

To add to @Christian's comment:

Replace all single or double quotes in a string:

s = "'asdfa sdfa'"

import re
re.sub("[\"\']", "", s)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.