Reputation: 1
x="3x^2+2x-1"
x=re.split(r"[\^]|([-])|[+]", x)
print(x)
#returns: ['3x', None, '2', None, '2x', '-', '1']
I thought it should return something like ['3x','2','2x','-','1']. Sorry, I'm sure I'm just misunderstanding re. Thanks!
Upvotes: 0
Views: 30
Reputation: 1090
x = [y for y in re.split(r"[\^]|([-])|[+]", x) if y != None]
I am not an RegEx wizard, but you can remove all Nones.
Upvotes: 1
Reputation: 522501
Your regex pattern used for splitting has a capture group in there, but it only includes the minus operator. Just split on the character class ([\^*/+-])
inside a capture group. This will split on any operator but will also include that operator in the output list.
x = "3x^2+2x-1"
x = re.split(r"([\^*/+-])", x)
print(x) # ['3x', '^', '2', '+', '2x', '-', '1']
Upvotes: 2