Reputation: 13329
string = "$hahahaha$hahahaha hello";
How can I remove everything between the 2 $'s and also the $'s so I end up with:
hahahaha hello
The $ could also be '@' or '*' or '&' or '?'
Upvotes: 4
Views: 21036
Reputation: 30985
You can use the following regex:
([$@*&?]).*?\1(.*)
And grab the 2nd capturing group
Upvotes: 3
Reputation: 180391
In [42]: s = "$hahahaha$hahahaha hello"
In [43]: " ".join(s.rsplit("$",1)[1:])
Out[43]: 'hahahaha hello'
In [44]: (re.split("[$@*&?]",s)[-1])
Out[44]: 'hahahaha hello'
Upvotes: 0
Reputation: 739
If you are not comfortable using regular expression, you can use find() method. Please check the following code:
>>> string = "$hahahaha$hello"
>>> ch = '$'
>>> pos_1 = string.find(ch)
>>> if pos_1 < len(string) - 2:
... pos_2 = string[pos_1+1:].find(ch) + pos_1 + 1
...
>>> if pos_2 < len(string) - 1:
... string = string[0:pos_1] + string[pos_2+1:]
... else:
... string = string[0:pos_1]
...
>>> string
'hello'
>>>
Upvotes: 3
Reputation: 25331
import re
text = "$hahahaha$hahahaha hello"
print text.replace(re.findall(r'\$(.*?)\$', text)[0],'').replace('$','')
but needs to be expanded for other characters besides $ and for multiple strings between the $ character.
Upvotes: 0
Reputation: 177
use a regular expression
import re
string = "$hahahaha$hahahaha hello"
stripped = re.sub("[$@*&?].*[$@*&?]", "", string)
print stripped
should output
hahahaha hello
Upvotes: 6
Reputation: 11730
import re
string = "$hahahaha$hello";
ma = re.search(r'([$@*&?])(.+)\1(.+)$', string)
print ma.group(2), ma.group(3)
Upvotes: 1