Cubedey
Cubedey

Reputation: 1

re.split parameters aren't working like guides say?

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

Answers (2)

Larry the Llama
Larry the Llama

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

Tim Biegeleisen
Tim Biegeleisen

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

Related Questions