How to take a string out of a string?

Let’s say we have a string:

string_a = “I want to return ‘this’ string”

Is there a way we can format string_a so that we can return this without indexing or using the word itself in a function (ex. you cannot use .remove(‘this’) or .split(‘this’). You can still use the function, it just cannot include ’this’

you could use regular expressions:

import re
my_str = "I want to return 'this' string"
result = re.findall(r"'(\w+)'", my_str)
print(result)

this will extract all words enclosed in apostrophes.

but why would you want this?

1 Like

You could also program a for loop to return everything between the single quotes.

How would you do that?

I am given:

string = "msg '(5+1)/2 = ', a    ; output message"

I need to return:

`’(5+1)/2 = 3’`

I’m not clear as to whether you want to preserve the quotes, but …

def between_quotes(s):
    ''' return the text from s
    that lies between single quotes,
    along with the integer value of the 
    resulting arithmetic expression.
    '''
    quote_found = False
    out_string = ''    
    for ch in s:
        if quote_found and not ch == "'":
            out_string += ch
        if ch == "'":
            quote_found = not quote_found        
    q = out_string.strip('= ')
    p = eval(q)
    out_string += str(int(p))

    return out_string

print(between_quotes("msg '(5+1)/2 = ', a    ; output message"))

Output:

(5+1)/2 = 3
1 Like

So basically, once a quote is found, characters are added to the out_string until another quote is found. I think thats how it works

1 Like

we can still use regular expression, we just need to match any character between the apostrophes:

import re
string = "msg '(5+1)/2 = ', a    ; output message"
result = re.findall(r"'(.*?)'", string)

Next time, please give a more descriptive post from the get go, so we can better understand the scope and complexity of the problem you are dealing with

now just a lot of additional information is added later.

Sorry, I didn’t think it would make a difference at first

If only the first and last quotes are the significant ones, then you could split it.

1 Like