Getting a string between two characters in python

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

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

and I need to put them in a StringFunction:

StringFunction(function, independent_variables=[vari])

where I need to get only "sin (x)" for the function and "x" for var. So it will look like this:

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

The problem is that I cannot get the function and variable. I 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)
Everything seems to give me nothing. Am I doing something wrong? All help is appreciated. Thank.
+5
source share
4 answers

Tweak way!

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

$- a special character in the regular expression (it indicates the end of the line). You need to avoid this:

>>> re.findall(r'\$(.*?)\$', '$sin (x)$ is an function of x')
['sin (x)']
+6

start:

end = string.index(end_marker, start + 1)

:

>>> start_marker = end_marker = '$'
>>> string = '$sin (x)$ is an function of x'
>>> start = string.index(start_marker) + len(start_marker)
>>> end = string.index(end_marker, start + 1)
>>> string[start:end]
'sin (x)'

For your regular expressions, the character is $interpreted as an anchor, not a literal character. Choose it according to the literal $(and look for things that are not $instead ":

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

which gives:

>>> import re
>>> re.findall('\$([^$]*)\$', string)
['sin (x)']

$()$Otherwise, the regular expression cannot match anything between brackets, even if you escaped characters $.

+3
source

If you want to cut a string between two identical characters (i.e.! 234567890!), You can use

   line_word = line.split('!')
   print (line_word[1])
0
source

All Articles