getting string between 2 characters in python

bellere picture bellere · Feb 23, 2013 · Viewed 40.5k times · Source

I need to get certain words out from a string in to a new format. For example, I call the function with the input:

text2function('$sin (x)$ is an function of x')

and I need to put them into a StringFunction:

StringFunction(function, independent_variables=[vari])

where I need to get just 'sin (x)' for function and 'x' for vari. So it would look like this finally:

StringFunction('sin (x)', independent_variables=['x']

problem is, I can't seem to obtain function and vari. I have tried:

start = string.index(start_marker) + len(start_marker)
end = string.index(end_marker, start)
return string[start:end]

and

r = re.compile('$()$')
m = r.search(string)
if m:
     lyrics = m.group(1)

and

send = re.findall('$([^"]*)$',string)

all seems to seems to give me nothing. Am I doing something wrong? All help is appreciated. Thanks.

Answer

Soorej P picture Soorej P · May 30, 2013

Tweeky way!

>>> char1 = '('
>>> char2 = ')'
>>> mystr = "mystring(123234sample)"
>>> print mystr[mystr.find(char1)+1 : mystr.find(char2)]
123234sample