luscv
luscv

Reputation: 1

How can I split a string with two different spacings?

I want to separate some words of a string but there is two types of divisions in the line using python: Example of the string:

add $s2, $s0, $s1

I want to separate in:

"add", "$s2", "$s0", "$s1"

but with data.split() function I can only Split them with "," or " ", but in this case between add and $s2 it doesn't have "," only " ".

arq = open('entrada.asm', 'r')
text = arq.readlines()
for line in text:
    (inst) = line.split(" ")
    (reg1, reg2, reg3) = line.split(",")
    print(inst, reg1, reg2, reg3)
arq.close()

Upvotes: 0

Views: 36

Answers (1)

Chris
Chris

Reputation: 29742

Use re.split:

import re
re.split('[ ,]+', 'add $s2, $s0, $s1')

Output:

['add', '$s2', '$s0', '$s1']

Upvotes: 1

Related Questions