Reputation: 1
s = "[(0, '0.105*\"function\" + 0.032*\"program\" + 0.024*\"location\"')]"
This is a string I have. How do I separate strings like "function", "program", "location" using regex in python?
I expect the output in terms of list i.e.
lst = ['function', 'program', 'location']
Upvotes: 0
Views: 51
Reputation: 36360
You can use re
module for that, but - at least for that sample data you provided - do not have to use it to get desired output, as just str
methods will suffice. That is:
s = "[(0, '0.105*\"function\" + 0.032*\"program\" + 0.024*\"location\"')]"
lst = [i for i in s.split('"') if i.isalpha()]
print(lst)
Output:
['function', 'program', 'location']
This code simply split
s
at "
and then pick str
s which consist solely of alphabetic characters and have length no less than 1
.
Upvotes: 1
Reputation: 44828
Try this:
>>> re.findall(r'"([^"]*)"', s)
['function', 'program', 'location']
Upvotes: 1
Reputation: 1547
import re
s = "[(0, '0.105*\"function\" + 0.032*\"program\" + 0.024*\"location\"')]"
groups = re.findall("\"([a-z]+?)\"",s) # get groups of all letters which are between two `"`
print(groups) # -> ['function', 'program', 'location']
Upvotes: 0